如何使用camel-jackson将JSONArray转换为对象列表

2022-09-01 04:10:58

我有json数组的字符串,如下所示

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

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

 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]

有人可以告诉我错过了什么或做错了什么吗?


答案 1

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

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

这表示一个对象,该对象包含一个属性 Compemployes,该属性是 Employee 的列表。在这种情况下,您应该创建该对象,如下所示:

class EmployeList{
    private List<Employe> compemployes;
    (with getter an setter)
}

要反序列化 json,只需执行以下操作:

EmployeList employeList = mapper.readValue(jsonString,EmployeList.class);

如果你的json应该直接代表一个员工列表,它应该看起来像这样:

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

最后一句话:

List<Employee> list2 = mapper.readValue(jsonString, 
TypeFactory.collectionType(List.class, Employee.class));

TypeFactory.collectionType已弃用,您现在应该使用如下内容:

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

答案 2
/*
 It has been answered in http://stackoverflow.com/questions/15609306/convert-string-to-json-array/33292260#33292260
 * put string into file jsonFileArr.json
 * [{"username":"Hello","email":"hello@email.com","credits"
 * :"100","twitter_username":""},
 * {"username":"Goodbye","email":"goodbye@email.com"
 * ,"credits":"0","twitter_username":""},
 * {"username":"mlsilva","email":"mlsilva@email.com"
 * ,"credits":"524","twitter_username":""},
 * {"username":"fsouza","email":"fsouza@email.com"
 * ,"credits":"1052","twitter_username":""}]
 */

public class TestaGsonLista {

public static void main(String[] args) {
Gson gson = new Gson();
 try {
    BufferedReader br = new BufferedReader(new FileReader(
            "C:\\Temp\\jsonFileArr.json"));
    JsonArray jsonArray = new JsonParser().parse(br).getAsJsonArray();
    for (int i = 0; i < jsonArray.size(); i++) {
        JsonElement str = jsonArray.get(i);
        Usuario obj = gson.fromJson(str, Usuario.class);
        //use the add method from the list and returns it.
        System.out.println(obj);
        System.out.println(str);
        System.out.println("-------");
    }
 } catch (IOException e) {
    e.printStackTrace();
 }
}