gnj*_*ago 22 java json jackson
JSON字符串如下
{
"rank":"-text_relevance",
"match-expr":"(label 'star wars')",
"hits":{
"found":7,
"start":0,
"hit":[
{"id":"tt1185834",
"data":{
"actor":["Abercrombie, Ian","Baker, Dee","Burton, Corey"],
"title":["Star Wars: The Clone Wars"]
}
},
.
.
.
{"id":"tt0121766",
"data":{
"actor":["Bai, Ling","Bryant, Gene","Castle-Hughes, Keisha"],
"title":["Star Wars: Episode III - Revenge of the Sith"]
}
}
]
},
"info":{
"rid":"b7c167f6c2da6d93531b9a7b314ad030b3a74803b4b7797edb905ba5a6a08",
"time-ms":2,
"cpu-time-ms":0
}
}
Run Code Online (Sandbox Code Playgroud)
它有很多字段,但我只想要数据字段.这不起作用:
mapper.readvalue(jsonString,Data.class);
Run Code Online (Sandbox Code Playgroud)
如何让杰克逊只阅读"数据"字段?
小智 32
Jackson 2.3现在有一个你可以使用的JsonPointer类.他们在发布的快速概述中有一个简单的例子.
用法很简单:对于JSON之类的
Run Code Online (Sandbox Code Playgroud){ "address" : { "street" : "2940 5th Ave", "zip" : 980021 }, "dimensions" : [ 10.0, 20.0, 15.0 ] }你可以使用如下表达式:
Run Code Online (Sandbox Code Playgroud)JsonNode root = mapper.readTree(src); int zip =root.at("/address/zip").asIntValue(); double height = root.add("/dimensions/1").asDoubleValue();// assuming it's the second number in there
pb2*_*b2q 15
我认为最简单的方法是使用Jackson TreeModel:让杰克逊将JSON输入解析为一个JsonNode对象然后进行查询,假设有一些数据结构知识.这样,您可以忽略大部分数据,向下走到JsonNodes您想要的数据.
// String input = The JSON data from your question
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(input.getBytes(), JsonNode.class);
// can also use ArrayNode here, but JsonNode allows us to get(index) line an array:
JsonNode hits = rootNode.get("hits");
// can also use ObjectNodes here:
JsonNode oneHit = null;
JsonNode dataObj = null;
int idx = 0;
Data data = null;
if (hits != null)
{
hits = hits.get("hit");
if (hits != null)
{
while ((oneHit = hits.get(idx)) != null)
{
dataObj = oneHit.get("data");
System.out.println("Data[" + idx + "]: " + dataObj);
idx++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Data[0]: {"id":"tt1185834","data":{"actor":["Abercrombie, Ian","Baker, Dee","Burton, Corey"],"title":["Star Wars: The Clone Wars"]}}
Data[1]: {"id":"tt0121766","data":{"actor":["Bai, Ling","Bryant, Gene","Castle-Hughes, Keisha"],"title":["Star Wars: Episode III - Revenge of the Sith"]}}
Run Code Online (Sandbox Code Playgroud)
您仍然可以使用您的Data类实现,但我相信这将需要获取String代表每个data- 如上所述依赖toString或使用JsonNode.getText()- 并使用以下方法重新解析它ObjectMapper:
mapper.readValue(dataArray, Data.class));
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用Jackson Streaming模型,并自己拦截节点,直到您看到标记每个data元素开头的输入部分,然后objectMapper.readValue为每个字符串使用字符串并调用内容.
| 归档时间: |
|
| 查看次数: |
25705 次 |
| 最近记录: |