yellavon
yellavon

Reputation: 2881

Deserialize JSON string into a List of POJOs

Here is my code for deserializing the response I get back from a Google App Engine Cloud Endpoint:

String jsonString = IOUtils.toString(
    httpResponse.getEntity().getContent(), "UTF-8");

ObjectMapper mapper = new ObjectMapper();
ArrayList<myPOJO> myList= 
    mapper.readValue(jsonString, new TypeReference<ArrayList<MyPOJO>>(){});

jsonString looks like this:

{
  "items" : [ {
    "id" : "12345",
    "name" : "test1"
  }, {
    "id" : "121212",
    "name" : "test2"
  } ]
}

But I am getting this error:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token at [Source: java.io.StringReader@547a7880; line: 1, column: 1]

What is the proper way to deserialize this JSON into a List of POJOs with Jackson?

Upvotes: 3

Views: 3431

Answers (2)

Michał Ziober
Michał Ziober

Reputation: 38665

You have to create root POJO for your JSON root object. For example:

class Root {

    private List<Entity> items;

    //getters, setters, toString, etc
}

class Entity {

    private long id;
    private String name;

    //getters, setters, toString, etc
}

Simple app:

ObjectMapper mapper = new ObjectMapper();
Root list = mapper.readValue(json, Root.class);
System.out.println(list);

prints:

Root [items=[Entity [id=12345, name=test1], Entity [id=121212, name=test2]]]

Upvotes: 0

ravikumar
ravikumar

Reputation: 893

try deserializing directly with the mapper

String jsonString = IOUtils.toString(
        httpResponse.getEntity().getContent(), "UTF-8");

    ObjectMapper mapper = new ObjectMapper();

    List<MyPOJO> myList= mapper.convertValue(jsonString, mapper.getTypeFactory().constructCollectionType(List.class, MyPOJO.class));

Upvotes: 1

Related Questions