Deserialize JSON in ArrayList <POJO> using Jackson

I have a Java MyPojo class that interests me in JSON deserialization. I set up a special MixIn class, MyPojoDeMixIn , to help me deserialize. MyPojo only has int and String instance variables combined with the right getters and setters. MyPojoDeMixIn looks something like this:

 public abstract class MyPojoDeMixIn { MyPojoDeMixIn( @JsonProperty("JsonName1") int prop1, @JsonProperty("JsonName2") int prop2, @JsonProperty("JsonName3") String prop3) {} } 

In my test client, I do the following, but of course it does not work at compile time, because there is a JsonMappingException related to type mismatch.

 ObjectMapper m = new ObjectMapper(); m.getDeserializationConfig().addMixInAnnotations(MyPojo.class,MyPojoDeMixIn.class); try { ArrayList<MyPojo> arrayOfPojo = m.readValue(response, MyPojo.class); } catch (Exception e) { System.out.println(e) } 

I know that I could alleviate this problem by creating a "Response" object in which there is only an ArrayList<MyPojo> , but then I would have to create these few useless objects for each individual type that I want to return.

I also looked online at JacksonInFiveMinutes , but I scared to understand the information about Map<A,B> and how it relates to my problem. If you can’t tell, I am completely new to Java and come from the background of Obj-C. They specifically mention:

In addition to binding to POJOs and "simple" types, there is one additional option: binding to universal (typed) containers. This case requires special handling due to the so-called Type Erasure (used by Java to implement generics in a somewhat backward compatible way), which prevents you from using something like Collection.class (which does not compile).

So, if you want to bind data to a map, you will need to use:

 Map<String,User> result = mapper.readValue(src, new TypeReference<Map<String,User>>() { }); 

How can I deserialize directly on an ArrayList ?

+70
java json jackson mapping
Mar 22 2018-12-22T00:
source share
5 answers

You can deserialize directly to a list using the TypeReference shell. Method Example:

 public static <T> T fromJSON(final TypeReference<T> type, final String jsonPacket) { T data = null; try { data = new ObjectMapper().readValue(jsonPacket, type); } catch (Exception e) { // Handle the problem } return data; } 

And used this way:

 final String json = ""; Set<POJO> properties = fromJSON(new TypeReference<Set<POJO>>() {}, json); 

Type Link Javadoc

+122
Mar 22 '12 at 19:53
source share

Another way is to use the array as a type, for example:

 ObjectMapper objectMapper = new ObjectMapper(); MyPojo[] pojos = objectMapper.readValue(json, MyPojo[].class); 

This way you avoid all the problems with the Type object, and if you really need a list, you can always convert the array to a list:

 List<MyPojo> pojoList = Arrays.asList(pojos); 

IMHO it is much readable.

And to make it a real list (which can be changed, see the limitations of Arrays.asList() ), simply do the following:

 List<MyPojo> mcList = new ArrayList<>(Arrays.asList(pojos)); 
+78
Mar 10 '16 at 15:04
source share

This option looks simpler and more elegant.

 CollectionType typeReference = TypeFactory.defaultInstance().constructCollectionType(List.class, Dto.class); List<Dto> resultDto = objectMapper.readValue(content, typeReference); 
+15
Feb 25 '17 at 15:47
source share

I have the same problem too. I have json that needs to be converted to an ArrayList.

The account is as follows.

 Account{ Person p ; Related r ; } Person{ String Name ; Address a ; } 

All of the above classes were annotated correctly. I tried TypeReference> () {} but it does not work.

It gives me an Arraylist, but an ArrayList has an associated HashMap that contains some more associated hashmaps containing the final values.

My code is as follows:

 public T unmarshal(String responseXML,String c) { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JacksonAnnotationIntrospector(); mapper.getDeserializationConfig().withAnnotationIntrospector(introspector); mapper.getSerializationConfig().withAnnotationIntrospector(introspector); try { this.targetclass = (T) mapper.readValue(responseXML, new TypeReference<ArrayList<T>>() {}); } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return this.targetclass; } 

I finally solved the problem. I can convert List to Json String directly to ArrayList as follows:

 JsonMarshallerUnmarshaller<T>{ T targetClass ; public ArrayList<T> unmarshal(String jsonString) { ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JacksonAnnotationIntrospector(); mapper.getDeserializationConfig().withAnnotationIntrospector(introspector); mapper.getSerializationConfig().withAnnotationIntrospector(introspector); JavaType type = mapper.getTypeFactory(). constructCollectionType(ArrayList.class, targetclass.getClass()) ; try { Class c1 = this.targetclass.getClass() ; Class c2 = this.targetclass1.getClass() ; ArrayList<T> temp = (ArrayList<T>) mapper.readValue(jsonString, type); return temp ; } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null ; } } 
+3
Feb 05 '13 at 1:04
source share

This works for me.

 @Test public void cloneTest() { List<Part> parts = new ArrayList<Part>(); Part part1 = new Part(1); parts.add(part1); Part part2 = new Part(2); parts.add(part2); try { ObjectMapper objectMapper = new ObjectMapper(); String jsonStr = objectMapper.writeValueAsString(parts); List<Part> cloneParts = objectMapper.readValue(jsonStr, new TypeReference<ArrayList<Part>>() {}); } catch (Exception e) { //fail("failed."); e.printStackTrace(); } //TODO: Assert: compare both list values. } 
0
Aug 22 '18 at 14:55
source share



All Articles