我有以下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完全反序列化为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的其他方法的更多信息。
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);
您可以使用DSM流解析库来解析复杂的json和XML文档。DSM只解析一次数据,不会将所有数据加载到内存中。
假设我们有一个Page类来反序列化给定的json数据。
页面类
public class Page {
private String pageName;
private String pageImage;
private List<Sting> postIds;
// getter/setter
}
创建一个yaml Mapping文件。
result:
type: object # result is array
path: /posts
fields:
pageName:
path: /pageInfo/pageName
pageImage:
path: /pageInfo/pagePic
postIds:
path: post_id
type: array
使用DSM提取字段。
DSM dsm=new DSMBuilder(new File("path-to-yaml-config.yaml")).create(Page.class);
Page page= (Page)dsm.toObject(new path-to-json-data.json");
页面变量序列化为json:
{
"pageName" : "abc",
"pageImage" : "http://example.com/content.jpg",
"postIds" : [ "123456789012_123456789012" ]
}
DSM非常适合处理复杂的json和xml。