Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize JSON file starting with an array in Jackson?

Tags:

I have a Json file that looks like this:

[     { "field":"val" }, .... ] 

I have Java object representing single object and collection of them:

public class Objects{      public Collection<List> myObject; } 

I would like to deserialize JSON using ObjectMapper.

ObjectMapper mapper = new ObjectMapper(); mapper.readValue(in, Objects.class); 

But I get:

11-24 23:19:19.828: W/UpdateService(6084): org.codehaus.jackson.map.JsonMappingException:  Can not deserialize instance of com.project.my.Objects out of START_ARRAY token 
like image 783
pixel Avatar asked Nov 24 '11 22:11

pixel


People also ask

Does Jackson preserve array order?

Jackson mapper fill the ArrayList maintaining the order of JSON. If you want a different order you can use the annotation @JsonPropertyOrder.

How does Jackson read JSON array?

Reading JSON from a File Thankfully, Jackson makes this task as easy as the last one, we just provide the File to the readValue() method: final ObjectMapper objectMapper = new ObjectMapper(); List<Language> langList = objectMapper. readValue( new File("langs. json"), new TypeReference<List<Language>>(){}); langList.


1 Answers

Try

   mapper.readValue(in, ObjectClass[].class); 

Where ObjectClass is something like:

  public class ObjectClass {     String field;      public ObjectClass() { }      public void setField(String value) {       this.field = value;     }   } 

Note: in your posted version of the Objects class, you're declaring a Collection of Lists (i.e. a list of lists), which is not what you want. You probably wanted a List<ObjectClass>. However, it's much simpler to just do YourObject[].class when deserializing with Jackson, and then converting into a list afterwards.

like image 121
dmon Avatar answered Oct 02 '22 08:10

dmon