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 thereadTree()
method.This will give you a
JsonNode
. Grab the results as anotherJsonNode
and cycle through the array: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: