如何使用骆驼杰克逊将

如何使用骆驼杰克逊将

本文介绍了如何使用骆驼杰克逊将 JSONArray 转换为对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 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 ofEmployee. 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));

这篇关于如何使用骆驼杰克逊将 JSONArray 转换为对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 22:57