如何使用JacksonparsingJSONstring到数组

我有一个String与下面的值:

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

和以下class级:

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

我想parsing它到一个List<SomeClass>SomeClass[]

使用Jackson ObjectMapper的最简单的方法是什么?

我终于明白了:

 List<SomeClass> someClassList = mapper.readValue(jsonString, typeFactory.constructCollectionType(List.class, SomeClass.class)); 

另一个答案是正确的,但为了完整性,这里有其他的方法:

 List<SomeClass> list = mapper.readValue(jsonString, new TypeReference<List<SomeClass>>() { }); SomeClass[] array = mapper.readValue(jsonString, SomeClass[].class); 

数组的完整示例。 将“ constructArrayType() ”replace为“ constructCollectionType() ”或您需要的任何其他types。

 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); } }