How to parse a JSON string in an array using Jackson

I have a String with the following value:

 [{"key1":"value11", "key2":"value12"},{"key1":"value21", "key2":"value22"}] 

And the following class:

 public class SomeClass { private String key1; private String key2; /* ... getters and setters omitted ...*/ } 

And I want to List<SomeClass> it on a List<SomeClass> or SomeClass[]

What is the easiest way to do this using Jackson ObjectMapper ?

+71
java json jackson
Aug 30 '11 at 16:01
source share
3 answers

I finally got it:

 ObjectMapper objectMapper = new ObjectMapper(); TypeFactory typeFactory = objectMapper.getTypeFactory(); List<SomeClass> someClassList = objectMapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class)); 
+114
Aug 30 '11 at 16:26
source share

Another answer is correct, but for completeness, here are other ways:

 List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { }); SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class); 
+65
Aug 31 '11 at 11:55
source share

Full example with an array. Replace "constructArrayType ()" with "constructCollectionType ()" or whatever type you need.

 import java.io.IOException; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; public class Sorting { private String property; private String direction; public Sorting() { } public Sorting(String property, String direction) { this.property = property; this.direction = direction; } public String getProperty() { return property; } public void setProperty(String property) { this.property = property; } public String getDirection() { return direction; } public void setDirection(String direction) { this.direction = direction; } public static void main(String[] args) throws JsonParseException, IOException { final String json = "[{\"property\":\"title1\", \"direction\":\"ASC\"}, {\"property\":\"title2\", \"direction\":\"DESC\"}]"; ObjectMapper mapper = new ObjectMapper(); Sorting[] sortings = mapper.readValue(json, TypeFactory.defaultInstance().constructArrayType(Sorting.class)); System.out.println(sortings); } } 
+3
Jun 27 '14 at 19:58
source share



All Articles