我有以下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。
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);
您需要使用JsonNode和来自jackson库的ObjectMapper类来获取Json树的节点。在pom.xml中添加以下依赖项以获得对Jackson类的访问权。
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
你应该尝试下面的代码,这将工作:
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
class JsonNodeExtractor{
public void convertToJson(){
String filepath = "c:\\data.json";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(filepath);
// create a JsonNode for every root or subroot element in the Json String
JsonNode pageInfoRoot = node.path("pageInfo");
// Fetching elements under 'pageInfo'
String pageName = pageInfoRoot.path("pageName").asText();
String pagePic = pageInfoRoot.path("pagePic").asText();
// Now fetching elements under posts
JsonNode postsNode = node.path("posts");
String post_id = postsNode .path("post_id").asText();
String nameOfPersonWhoPosted = postsNode
.path("nameOfPersonWhoPosted").asText();
}
}
org。Json库易于使用。
只要记住(在强制转换或使用getJSONObject和getJSONArray等方法时)JSON表示法
[…]表示一个数组,因此库将把它解析为JSONArray
{…}表示一个对象,因此库将把它解析为JSONObject
示例代码如下:
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
}
你可以从以下几个方面找到更多的例子
可下载的jar: http://mvnrepository.com/artifact/org.json/json
您可以使用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。