我有以下JSON文本。我如何解析它以获得pageName, pagePic, post_id等的值?
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
JSON是这样的:
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
}
}
Java类
class PageInfo {
private String pageName;
private String pagePic;
// Getters and setters
}
将此JSON转换为Java类的代码。
PageInfo pageInfo = JsonPath.parse(jsonString).read("$.pageInfo", PageInfo.class);
Maven
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
org。Json库易于使用。
只要记住(在强制转换或使用getJSONObject和getJSONArray等方法时)JSON表示法
[…]表示一个数组,因此库将把它解析为JSONArray
{…}表示一个对象,因此库将把它解析为JSONObject
示例代码如下:
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
}
你可以从以下几个方面找到更多的例子
可下载的jar: http://mvnrepository.com/artifact/org.json/json
可以使用Apache @Model注释创建表示JSON文件结构的Java模型类,并使用它们访问JSON树中的各种元素。与其他解决方案不同,该解决方案完全没有反射,因此适用于不可能反射或开销很大的环境。
有一个示例Maven项目展示了这种用法。首先它定义了结构:
@Model(className="RepositoryInfo", properties = {
@Property(name = "id", type = int.class),
@Property(name = "name", type = String.class),
@Property(name = "owner", type = Owner.class),
@Property(name = "private", type = boolean.class),
})
final class RepositoryCntrl {
@Model(className = "Owner", properties = {
@Property(name = "login", type = String.class)
})
static final class OwnerCntrl {
}
}
然后它使用生成的RepositoryInfo和Owner类来解析所提供的输入流,并在此过程中获取某些信息:
List<RepositoryInfo> repositories = new ArrayList<>();
try (InputStream is = initializeStream(args)) {
Models.parse(CONTEXT, RepositoryInfo.class, is, repositories);
}
System.err.println("there is " + repositories.size() + " repositories");
repositories.stream().filter((repo) -> repo != null).forEach((repo) -> {
System.err.println("repository " + repo.getName() +
" is owned by " + repo.getOwner().getLogin()
);
})
就是这样!除此之外,这里还有一个生动的要点,展示了类似的例子以及异步网络通信。