AJT_82 AJT_82 - 2 months ago 20
Java Question

JSON to POJO (nested) using Jackson

This shouldn't be such a tricky question, but I'm a newbie, and I haven't found an example that helps me.

I have JSON like this (very simplified):

"documents": [
"title": "Jobs",
"abstract": "<span class=\"hit\">Jobs</span> may refer to:\n\n* Steve <span class=\"hit\">Jobs</span> (1955–2011), co-founder and former CEO of consumer electronics company...<br />",
"id": "Jobs",
"url": "http://en.wikipedia.org/wiki/Jobs"

"sessionid": "0d12681c-2f98-4d67-a044-d9baab260b09",
"q": "Jobs",

This needs to be converted to a Java Object

Looks like this:

public class SearchQuery {

private List<SearchQueryDocument> documents = new ArrayList<SearchQueryDocument>
private sessionid;
private q;

//getters and setters


And with a class

public class SearchQueryDocument {

private String title;

private String abstractText

private String id;
private String url;

//getters and setters


When I convert the JSON like this:

ObjectMapper mapper = new ObjectMapper();
SearchQuery sq = mapper.readValue(output, SearchQuery.class);

//prints correct sessionid!

//doesn't work
//prints: ['my package name here'.SearchQueryDocument@385073cf]

I realize the problem lies with that the "documents" is a List of
, but I don't know how to solve this?? I've found some nice and helpful examples online like MKYong, but never with this that there is a nested class involved. Tried doing searches here on SO as well. Maybe I'm using the wrong search keywords since I suspect there should be many examples out there...

Thankful for any help!

5er 5er

You need to iterate trough sq.documents and print them out. Do it with for loop or with Iterable.

List<SearchQueryDocument> documents = sq.getDocumnets()

for (String document : documents) {

You can also do:

for (String document : documents) {

but in this case you need to override toString method in SearchQueryDocument.class