简体   繁体   中英

Parsing JSON Bing results with Jackson

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM