杰克逊 - Unmarshall收集/数组
最后修改:2019年12月23日
1.概述
本教程将显示如何将JSON数组命中到Java数组或使用Jackson 2收集。
如果你想深入挖掘和学习你可以用杰克逊2做的其他很酷的东西- 前往主要的杰克逊教程。
2. Unmarshall到Array
杰克逊可以轻松地反序列化为Java数组:
@test public void给gensonArray_WhendeserializingAsAray_thencorrect()抛出jsonparseexception,jsonmappedException,ioException {objectMapper映射器= new objectMapper();列表 listofdtos = lists.newarraylist(新的mydto(“a”,1,true),新的mydto(“bc”,3,false));字符串jsonarray = mapper.writevalueastring(listofdtos);// [{“stringValue”:“a”,“intvalue”:1,“booleanvalue”:true},// {stringvalue“:”bc“,”intvalue“:3,”booleanvalue“:false}] mydto[] AsArray = Mapper.ReadValue(JSONARRAY,MYDTO []。类);Assertthat(Asarray [0],instanceof(mydto.class));}
3.联原班汇集
读取同一JSON数组到Java集合中有点困难 - 默认情况下,杰克逊将无法获得完整的通用类型信息而是将创建一个链接的集合Hashmap.实例:
@test public void给gensonarray_whendeserializingaslistwithnotypeinfo_thennotcorrect()抛出jsonparseexception,jsonmappedexception,ioException {objectMapper映射器= new objectMapper();列表 listofdtos = lists.newarraylist(新的mydto(“a”,1,true),新的mydto(“bc”,3,false));字符串jsonarray = mapper.writevalueastring(listofdtos);列表 aslist = mapper.readvalue(jsonArray,list.class);asserthat((对象)Aslist.get(0),instanceof(linkedhashmap.class));}
有两种方式帮助杰克逊了解正确的类型信息- 我们可以使用典型图书馆提供了这个非常目的:
@test public void给gensonarray_whendeserializingaslistwithtypereferencedhelp_thencorrect()抛出jsonparseexception,jsonmappexception,ioException {objectMapper映射器= new objectMapper();列表 listofdtos = lists.newarraylist(新的mydto(“a”,1,true),新的mydto(“bc”,3,false));字符串jsonarray = mapper.writevalueastring(listofdtos);列表 aslist = mapper.readvalue(jsonArray,新的TypeReference >(){});asserthat(Aslist.get(0),instanceof(mydto.class));}
或者我们可以使用超载ReadValue.接受一个方法javatype.:
@test publi void给gensonArray_WhendeserializationAslistwithjavatypehelp_thengorrect()抛出jsonparseexception,jsonmappexception,ioException {objectMapper映射器= new objectMapper();列表 listofdtos = lists.newarraylist(新的mydto(“a”,1,true),新的mydto(“bc”,3,false));字符串jsonarray = mapper.writevalueastring(listofdtos);collectiontype javatype = mapper.gettypefactory().constructCollectionType(list.class,mydto.class);列表 aslist = mapper.readvalue(jsonArray,Javatype);asserthat(Aslist.get(0),instanceof(mydto.class));}
最后一个注意事项是my类需要拥有No-args默认构造函数 - 如果没有,杰克逊将无法实例化它:
com.fasterxml.jackson.databind.jsonMappingException:找不到类型[简单类型,类org.baeldung.jackson.ignore.mydto]找不到合适的构造函数:无法从JSON金宝搏188体育对象实例化(需要添加/启用类型信息?)
4。结论
将JSON数组映射到Java Collections是jackson用于使用的常用任务之一,以及这些解决方案对正确的,型式安全的映射至关重要。
实现所有这些示例和代码片段可以在我们的中找到GitHub项目- 这是一个基于Maven的项目,因此应该易于导入和运行。