繁体   English   中英

Java; 杰克逊 解析数组json字符串的数组

[英]Java; Jackson; Parsing the array of array json string

我在使用jackson api将json下方解析为java对象时遇到问题。

Json String
[
  [
    {
      "id": "6555",
      "fname": "hello",
      "lname": "test"
    },
    {
      "id": "6588",
      "fname": "world",
      "lname": "test"
    }
  ]
]

我在pojos下面创建了(删除了setter和getter)。

public class Result {
   List<Student> studentList;
}

public class Student{
   private String id;
   private String fname;
   private String lname;
}

ObjectMapper mapper = new ObjectMapper();
List<Result > responseList = mapper.readValue(jsonStr, new TypeReference<List<Result>>(){});

杰克逊有抛出异常

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of out of START_ARRAY token at [Source:

我是否需要对Result对象使用任何特定的杰克逊注释?

您不需要Result类,这是多余的。 您需要将其解析为List<List<Student>>因为您的json结构以数组开头并包含另一个数组。

这是解析您的方法:

ObjectMapper mapper = new ObjectMapper();
try {
    List<Result> responseList = mapper.readValue(
            Files.readAllBytes(Paths.get("test.json")),
            new TypeReference<List<List<Student>>>() {});

} catch (IOException e) {
    e.printStackTrace();
}

输出:

在此处输入图片说明

如果我想编写JSON以匹配您定义的结构,则需要:

[ 
    { 
        "studentList": 
        [
            {
                "id": "6555",
                "fname": "hello",
                "lname": "test"
            },
            {
                "id": "6588",
                "fname": "world",
                "lname": "test"
            }
        ]
    }
]

基于您已布置的JSON,我希望Jackson将其视为List<List<Student>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM