如何使用骆驼杰克逊将 JSONArray 转换为对象列表

2022-01-19 00:00:00 json java jackson apache-camel

我的 json 数组字符串如下

Am having the String of json array as follow

{"Compemployes":[
    {
        "id":1001,
        "name":"jhon"
        },
        {
                "id":1002,
        "name":"jhon"
        }
]}

我想将此 jsonarray 转换为 List<Empolyee> .为此,我添加了 maven 依赖项camel-jackson",并为员工编写了 pojo 类.但是当我尝试运行下面的代码时

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

我遇到了以下异常.

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

推荐答案

问题不在于你的代码,而在于你的 json:

The problem is not in your code but in your json:

{"Compemployes":[{"id":1001,"name":"jhon"}, {"id":1002,"name":"jhon"}]}

this 表示一个包含属性 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 应该直接表示员工列表,它应该如下所示:

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 已被弃用,您现在应该使用类似:

TypeFactory.collectionType is deprecated you should now use something like:

List<Employee> list = mapper.readValue(jsonString,
TypeFactory.defaultInstance().constructCollectionType(List.class,  
   Employee.class));

相关文章