Jackson反序列化数组类型json值
Jackson 反序列化数组类型json值
本⽂介绍如何使⽤Jackson 2反序列化json数组值⾄Java 数组或集合。
反序列化为Array
Jackson可以很容易反序列化为Java数组:
@Test
public void givenJsonArray_whenDeserializingAsArray_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
List<MyDto> listOfDtos = wArrayList(
new MyDto("a", 1, true), new MyDto("bc", 3, false));
String jsonArray = mapper.writeValueAsString(listOfDtos);
// [{"stringValue":"a","intValue":1,"booleanValue":true},
// {"stringValue":"bc","intValue":3,"booleanValue":false}]
json值的类型有哪些MyDto[] asArray = adValue(jsonArray, MyDto[].class);
assertThat(asArray[0], instanceOf(MyDto.class));
}
反序列化为List
相⽐于数组,转Java Collection要稍微复杂点,缺省情况下Jackson不能获得完整的泛型信息,需要创建LinkedHashMap实例:
@Test
public void givenJsonArray_whenDeserializingAsListWithNoTypeInfo_thenNotCorrect()
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
List<MyDto> listOfDtos = wArrayList(
new MyDto("a", 1, true), new MyDto("bc", 3, false));
String jsonArray = mapper.writeValueAsString(listOfDtos);
List<MyDto> asList = adValue(jsonArray, List.class);
assertThat((Object) (0), instanceOf(LinkedHashMap.class));
}
有两种⽅法能帮助Jackson理解右边类型信息,使⽤Jackson提供的TypeReference实现:
@Test
public void givenJsonArray_whenDeserializingAsListWithTypeReferenceHelp_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
List<MyDto> listOfDtos = wArrayList(
new MyDto("a", 1, true), new MyDto("bc", 3, false));
String jsonArray = mapper.writeValueAsString(listOfDtos);
List<MyDto> asList = adValue(
jsonArray, new TypeReference<List<MyDto>>() { });
(0), instanceOf(MyDto.class));
}
或者能使⽤接收JavaType类型的重载readValue⽅法:
@Test
publi void givenJsonArray_whenDeserializingAsListWithJavaTypeHelp_thenCorrect()
throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
List<MyDto> listOfDtos = wArrayList(
new MyDto("a", 1, true), new MyDto("bc", 3, false));
String jsonArray = mapper.writeValueAsString(listOfDtos);
CollectionType javaType = TypeFactory()
.constructCollectionType(List.class, MyDto.class);
List<MyDto> asList = adValue(jsonArray, javaType);
(0), instanceOf(MyDto.class));
}
分为两步实现,⾸先 TypeFactory().constructCollectionType(List.class, MyDto.class) 获得CollectionType,然后调⽤readValue⽅法返回正确的类型列表对象。
最后需要说明的是MyDto类需要有缺省⽆参构造函数,否则Jackson实例化失败,错误信息如下:
com.fasterxml.jackson.databind.JsonMappingException:
No suitable constructor found for type [simple type, class org.baeldung.jackson.ignore.MyDto]:
can not instantiate from JSON object (need to add/enable type information?)
总结
将JSON数组映射到java集合是Jackson最常⽤的任务之⼀,关键是如何实现正确、类型安全的映射。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论