我有以下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"
}
]
}
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);
你可以使用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