我有以下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"
}
]
}
Java中有许多可用的JSON库。
最臭名昭著的是:Jackson, GSON, Genson, FastJson和org.json。
在选择任何库时,通常应该注意以下三点:
性能
易于使用(代码写起来简单易读)——这与功能有关。
对于移动应用:依赖/jar大小
特别是对于JSON库(以及任何序列化/反序列化库),数据绑定通常也很有趣,因为它消除了编写样板代码来打包/解包数据的需要。
对于1,看到这个基准:https://github.com/fabienrenaud/java-json-benchmark我做了使用JMH比较(杰克逊,gson, genson, fastjson, org。使用stream和databind api实现序列化器和反序列化器的性能。
第二,你可以在网上找到很多例子。上面的基准测试也可以作为例子的来源。
快速总结一下基准:杰克逊的表现比组织好5到6倍。json,比GSON好两倍以上。
对于您的特定示例,下面的代码将使用jackson解码json:
public class MyObj {
private PageInfo pageInfo;
private List<Post> posts;
static final class PageInfo {
private String pageName;
private String pagePic;
}
static final class Post {
private String post_id;
@JsonProperty("actor_id");
private String actorId;
@JsonProperty("picOfPersonWhoPosted")
private String pictureOfPoster;
@JsonProperty("nameOfPersonWhoPosted")
private String nameOfPoster;
private String likesCount;
private List<String> comments;
private String timeOfPost;
}
private static final ObjectMapper JACKSON = new ObjectMapper();
public static void main(String[] args) throws IOException {
MyObj o = JACKSON.readValue(args[0], MyObj.class); // assumes args[0] contains your json payload provided in your question.
}
}
如果你有任何问题请告诉我。
{
"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"
}
]
}
Java code :
JSONObject obj = new JSONObject(responsejsonobj);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts");
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......etc
}
主要有两种选择……
Object mapping. When you deserialize JSON data to a number of instances of:
1.1. Some predefined classes, like Maps. In this case, you don't have to design your own POJO classes. Some libraries: org.json.simple https://www.mkyong.com/java/json-simple-example-read-and-write-json/
1.2. Your own POJO classes. You have to design your own POJO classes to present JSON data, but this may be helpful if you are going to use them into your business logic as well. Some libraries: Gson, Jackson (see http://tutorials.jenkov.com/java-json/index.html)
映射的主要缺点是它会导致大量内存分配(以及GC压力)和CPU占用。
面向流的解析。例如,Gson和Jackson都支持这种轻量级解析。另外,您还可以查看一个自定义的、快速的、无gc的解析器示例https://github.com/anatolygudkov/green-jelly。在需要解析大量数据和对延迟敏感的应用程序中,更倾向于使用这种方式。
Quick-json解析器非常简单,灵活,快速,可定制。试一试
特点:
Compliant with JSON specification (RFC4627)
High-Performance JSON parser
Supports Flexible/Configurable parsing approach
Configurable validation of key/value pairs of any JSON Hierarchy
Easy to use # Very small footprint
Raises developer friendly and easy to trace exceptions
Pluggable Custom Validation support - Keys/Values can be validated by configuring custom validators as and when encountered
Validating and Non-Validating parser support
Support for two types of configuration (JSON/XML) for using quick-JSON validating parser
Requires JDK 1.5
No dependency on external libraries
Support for JSON Generation through object serialisation
Support for collection type selection during parsing process
它可以这样使用:
JsonParserFactory factory=JsonParserFactory.getInstance();
JSONParser parser=factory.newJsonParser();
Map jsonMap=parser.parseJson(jsonString);
为了便于示例,让我们假设您有一个只有名称的Person类。
private class Person {
public String name;
public Person(String name) {
this.name = name;
}
}
谷歌GSON (Maven)
我个人最喜欢的JSON对象序列化/反序列化。
Gson g = new Gson();
Person person = g.fromJson("{\"name\": \"John\"}", Person.class);
System.out.println(person.name); //John
System.out.println(g.toJson(person)); // {"name":"John"}
更新
如果你想获取单个属性,你可以很容易地使用谷歌库:
JsonObject jsonObject = new JsonParser().parse("{\"name\": \"John\"}").getAsJsonObject();
System.out.println(jsonObject.get("name").getAsString()); //John
Org。JSON (Maven)
如果您不需要对象反序列化,而只是获得一个属性,您可以尝试org。json(或查看上面的GSON示例!)
JSONObject obj = new JSONObject("{\"name\": \"John\"}");
System.out.println(obj.getString("name")); //John
杰克逊(Maven)
ObjectMapper mapper = new ObjectMapper();
Person user = mapper.readValue("{\"name\": \"John\"}", Person.class);
System.out.println(user.name); //John
几乎所有给出的答案都要求在访问感兴趣的属性中的值之前,将JSON完全反序列化为Java对象。另一种不走这条路的替代方法是使用JsonPATH,它类似于JSON的XPath,允许遍历JSON对象。
它是一个规范,JayWay的优秀人员已经为该规范创建了一个Java实现,您可以在这里找到:https://github.com/jayway/JsonPath
所以基本上要使用它,把它添加到你的项目中,例如:
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>${version}</version>
</dependency>
并使用:
String pageName = JsonPath.read(yourJsonString, "$.pageInfo.pageName");
String pagePic = JsonPath.read(yourJsonString, "$.pageInfo.pagePic");
String post_id = JsonPath.read(yourJsonString, "$.pagePosts[0].post_id");
等等……
查看JsonPath规范页面,了解横向JSON的其他方法的更多信息。