用杰克逊解析JSON Bing的结果 [英] Parsing JSON Bing results with Jackson

查看:223
本文介绍了用杰克逊解析JSON Bing的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Jackson来解析JSON Bing的结果,但我对如何使用它有点困惑。以下是Bing收到的JSON示例:

I'd like to use Jackson to parse JSON Bing results, but I'm a little confused about how to use it. Here is an example of the JSON received from Bing:

{
   "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反序列化结果吗?

I really only need the data in the results array. This array could have anywhere from 0 to n results. Could someone provide an example that illustrates how to use Jackson to deserialize "Results"?

推荐答案

首先,将您的JSON读作树。实例化 ObjectMapper 并使用 readTree()方法读取您的JSON。

First, read your JSON as a tree. Instantiate an ObjectMapper and read your JSON using the readTree() method.

这将为您提供 JsonNode 。将结果作为另一个 JsonNode 抓取并循环遍历数组:

This will give you a JsonNode. Grab the results as another JsonNode and cycle through the array:

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
}

您还可以考虑使用JSON Schema实现验证输入。无耻插件: https://github.com/fge/json-schema-validator

You could also consider validating your input using a JSON Schema implementation. Shameless plug: https://github.com/fge/json-schema-validator

这篇关于用杰克逊解析JSON Bing的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆