Parsing JSON Bing results with Jackson

為{幸葍}努か 提交于 2019-12-12 20:15:50

问题


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":"[...]"
            }
         ]
      }
   }
}

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"?


回答1:


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

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
}

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




回答2:


The answer by fge is the way to go if you want to use Jackson directly.

If you'd like to work on pojos based on the json, then you could try json2pojo (https://github.com/wotifgroup/json2pojo - my shameless plug :) ) to take your sample json and generate the java classes.

Assuming you call the top level class "Bing", then you could use code like this:

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()) {
  ...
}


来源:https://stackoverflow.com/questions/8610657/parsing-json-bing-results-with-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!