如何使用骆驼杰克逊JSONArray转换为对象的名单 [英] how to convert JSONArray to List of Object using camel-jackson
问题描述
上午有JSON数组的字符串如下
Am having the String of json array as follow
{"Compemployes":[
{
"id":1001,
"name":"jhon"
},
{
"id":1002,
"name":"jhon"
}
]}
我想转换这款本jsonarray到列表< Empolyee>
。为了这个,我已经添加了Maven的依赖骆驼 - 杰克逊
,也写出员工POJO类。但是当我尝试运行我的下面code
i want to convert this this jsonarray to List<Empolyee>
. for this i had added the the maven dependency "camel-jackson
" and also write the pojo class for employee . but when i try to run my below code
ObjectMapper mapper = new ObjectMapper();
List<Employe> list = mapper.readValue(jsonString, TypeFactory.collectionType(List.class, Employe.class));
正在以下的异常。
am getting the following exception.
org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token
at [Source: java.io.StringReader@43caa144; line: 1, column: 1]
有人可以请告诉我是什么失踪或做点儿什么错
can someone pls tell what am missing or doing anyting wrong
推荐答案
问题是不是在你的code,但在你的JSON:
The problem is not in your code but in your json:
{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}
这再presents其中包含一个属性Compemployes这是列表的对象
雇员。在这种情况下,你应该创建一个对象,如:
this represents an object which contains a property Compemployes which is a list of Employee. In that case you should create that object like:
class EmployeList{
private List<Employe> compemployes;
(with getter an setter)
}
和反序列化JSON简单地做:
and to deserialize the json simply do:
EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);
如果您的JSON应该直接重新present员工的名单应该是这样的:
If your json should directly represent a list of employees it should look like:
[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]
最后一句话:
List<Employee> list2 = mapper.readValue(jsonString,
TypeFactory.collectionType(List.class, Employee.class));
TypeFactory.collectionType
是德precated 的你现在应该使用这样的:
TypeFactory.collectionType
is deprecated you should now use something like:
List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,
Employee.class));
这篇关于如何使用骆驼杰克逊JSONArray转换为对象的名单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!