Java 使用Jackson解析JSON Bing结果
我想使用Jackson解析JSON Bing结果,但我对如何使用它有点困惑。以下是从Bing收到的JSON示例:Java 使用Jackson解析JSON Bing结果,java,json,jackson,bing,Java,Json,Jackson,Bing,我想使用Jackson解析JSON Bing结果,但我对如何使用它有点困惑。以下是从Bing收到的JSON示例: { "SearchResponse":{ "Version":"2.2", "Query":{ "SearchTerms":"jackson json" }, "Web":{ "Total":1010000, "Offset":0, "Results":[
{
"SearchResponse":{
"Version":"2.2",
"Query":{
"SearchTerms":"jackson json"
},
"Web":{
"Total":1010000,
"Offset":0,
"Results":[
{
"Title":"Jackson JSON Processor - Home",
"Description":"News: 04-Nov-2011: Jackson 1.9.2 released; 23-Oct-2011: Jackson 1.9.1 released; 04-Oct-2011: Jackson 1.9.0 released (@JsonUnwrapped, value instantiators, value ...",
"Url":"http:\/\/jackson.codehaus.org\/",
"CacheUrl":"http:\/\/cc.bingj.com\/cache.aspx?q=jackson+json&d=4616347212909127&w=cbaf5322,11c785e8",
"DisplayUrl":"jackson.codehaus.org",
"DateTime":"2011-12-18T23:12:00Z",
"DeepLinks":"[...]"
}
]
}
}
}
我只需要结果数组中的数据。此数组可以有0到n个结果。有人能举个例子说明如何使用Jackson来反序列化“结果”吗?首先,将JSON作为一个树来阅读。实例化一个
ObjectMapper
,并使用readTree()
方法读取JSON
这将为您提供一个JsonNode
。将结果作为另一个JsonNode
抓取,并在数组中循环:
final ObjectMapper mapper = new ObjectMapper();
final JsonNode input = mapper.readTree(...);
final JsonNode results = input.get("SearchResponse").get("Web").get("Results");
/*
* Yes, this works: JsonNode implements Iterable<JsonNode>, and this will
* cycle through array elements
*/
for (final JsonNode element: results) {
// do whatever with array elements
}
final ObjectMapper mapper=new ObjectMapper();
最终JsonNode输入=mapper.readTree(…);
最终JsonNode结果=input.get(“SearchResponse”).get(“Web”).get(“结果”);
/*
*是的,这是可行的:JsonNode实现了Iterable,这将
*循环遍历数组元素
*/
for(最终JsonNode元素:结果){
//对数组元素执行任何操作
}
<>您也可以考虑使用JSON模式实现验证输入。无耻的插头:如果你想直接使用Jackson,fge的答案是正确的 如果您想使用基于json的POJO,那么可以尝试json2pojo(https://github.com/wotifgroup/json2pojo -我无耻的插件:))来获取示例json并生成java类 假设您调用顶级类“Bing”,那么您可以使用如下代码:
final ObjectMapper mapper = new ObjectMapper();
final Bing bing = ObjectMapper.readValue(..., Bing.class);
/*
* you may need a null check on getResults depending on what the
* Bing search returns for empty results.
*/
for (Result r : bing.getSearchResponse().getWeb().getResults()) {
...
}
results
看起来不像一个集合,但您似乎要对它进行迭代。是的,因为JsonNode
实现了Iterable
。在容器(即对象或数组)上调用时,它将循环遍历数组元素(数组)或属性值(对象)。在另一种JSON节点类型上,底层迭代器是空的。为什么要实例化ObjectMapper,然后静态引用它呢?非常酷的补充部分——感谢分享。似乎是Jackson数据绑定的好伴侣!