我有以下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"
}
]
}
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。
你可以使用Jayway JsonPath。下面是一个GitHub链接,包括源代码、pom细节和良好的文档。
https://github.com/jayway/JsonPath
请按照以下步骤操作。
步骤1:使用Maven在类路径中添加jayway JSON路径依赖项,或者下载JAR文件并手动添加它。
<dependency>
<groupId>com.jayway.jsonpath</groupId>
<artifactId>json-path</artifactId>
<version>2.2.0</version>
</dependency>
步骤2:请将输入的JSON保存为本示例的文件。在我的情况下,我将JSON保存为sampleJson.txt。注意,pageInfo和posts之间没有逗号。
步骤3:使用bufferedReader从上面的文件中读取JSON内容,并将其保存为String。
BufferedReader br = new BufferedReader(new FileReader("D:\\sampleJson.txt"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
br.close();
String jsonInput = sb.toString();
步骤4:使用jayway JSON解析器解析JSON字符串。
Object document = Configuration.defaultConfiguration().jsonProvider().parse(jsonInput);
第五步:像下面这样阅读细节。
String pageName = JsonPath.read(document, "$.pageInfo.pageName");
String pagePic = JsonPath.read(document, "$.pageInfo.pagePic");
String post_id = JsonPath.read(document, "$.posts[0].post_id");
System.out.println("$.pageInfo.pageName " + pageName);
System.out.println("$.pageInfo.pagePic " + pagePic);
System.out.println("$.posts[0].post_id " + post_id);
输出将是:
$.pageInfo.pageName = abc
$.pageInfo.pagePic = http://example.com/content.jpg
$.posts[0].post_id = 123456789012_123456789012
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);
首先,您需要选择一个实现库来执行此操作。
用于JSON处理的Java API (JSR 353)提供了使用对象模型和流API来解析、生成、转换和查询JSON的可移植API。
参考实现在这里:https://jsonp.java.net/
下面是JSR 353的实现列表:
哪些API实现了JSR-353 (JSON)
为了帮助你决定…我也找到了这篇文章:
http://blog.takipi.com/the-ultimate-json-library-json-simple-vs-gson-vs-jackson-vs-json/
如果您选择Jackson,这里有一篇关于使用Jackson在JSON和Java之间转换的好文章:https://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
希望能有所帮助!
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>