我有以下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"
}
]
}
为了便于示例,让我们假设您有一个只有名称的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
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);
由于还没有人提到它,这里是一个使用Nashorn (Java 8的JavaScript运行时部分,但在Java 11中已弃用)的解决方案的开始。
解决方案
private static final String EXTRACTOR_SCRIPT =
"var fun = function(raw) { " +
"var json = JSON.parse(raw); " +
"return [json.pageInfo.pageName, json.pageInfo.pagePic, json.posts[0].post_id];};";
public void run() throws ScriptException, NoSuchMethodException {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
engine.eval(EXTRACTOR_SCRIPT);
Invocable invocable = (Invocable) engine;
JSObject result = (JSObject) invocable.invokeFunction("fun", JSON);
result.values().forEach(e -> System.out.println(e));
}
性能比较
我编写的JSON内容包含三个数组,分别为20、20和100个元素。我只想从第三个数组中获取100个元素。我使用下面的JavaScript函数来解析和获取我的条目。
var fun = function(raw) {JSON.parse(raw).entries};
使用Nashorn运行一百万次调用需要7.5~7.8秒
(JSObject) invocable.invokeFunction("fun", json);
org。Json需要20~21秒
new JSONObject(JSON).getJSONArray("entries");
杰克逊用时6.5~7秒
mapper.readValue(JSON, Entries.class).getEntries();
在这种情况下,Jackson的性能比Nashorn好,后者的性能比org.json好得多。
Nashorn API比org更难使用。json或Jackson的。根据您的需求,Jackson和Nashorn都是可行的解决方案。
Jakarta (Java)企业版8包含JSON- b(用于JSON绑定的Java API)。因此,如果您使用的是Jakarta EE 8服务器,如Payara 5, JSON-B将是开箱即用的。
一个简单的例子,没有自定义配置:
public static class Dog {
public String name;
public int age;
public boolean bites;
}
// Create a dog instance
Dog dog = new Dog();
dog.name = "Falco";
dog.age = 4;
dog.bites = false;
// Create Jsonb and serialize
Jsonb jsonb = JsonbBuilder.create();
String result = jsonb.toJson(dog);
// Deserialize back
dog = jsonb.fromJson("{\"name\":\"Falco\",\"age\":4,\"bites\":false}", Dog.class);
您可以使用配置、注释、适配器和(反)序列化器自定义映射。
如果你没有使用Jakarta EE 8,可以随时安装JSON-B。
主要有两种选择……
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。在需要解析大量数据和对延迟敏感的应用程序中,更倾向于使用这种方式。