首页 > 解决方案 > 如何反序列化 JSON 数组以列出?

问题描述

我正在尝试使用杰克逊来消费 JSON。

我想绑定我的 json 的类是:-

KeyValueModel.class

public class KeyValueModel {

    private String k1;
    private String k2;
    public String getK1() {
        return k1;
    }
    public void setK1(String k1) {
        this.k1 = k1;
    }
    public String getK2() {
        return k2;
    }
    public void setK2(String k2) {
        this.k2 = k2;
    }
}

我想将 json 直接映射到我的模型列表,即 KeyValueModel

    @Test
    public void whenParsingJsonStringIntoList_thenCorrect() throws IOException {


    String jsonList = "{
  "count": 30,
  "data": [
    {
      "k1": "v1",
      "k2": "v2"
    },
    {
      "k1": "no",
      "k2": "yes"
    }
  ]
}";

ObjectMapper mapper = new ObjectMapper();
        JavaType listType = mapper.getTypeFactory().constructCollectionType(List.class, KeyValueModel.class);

        List<KeyValueModel> l = mapper.readValue(jsonList, listType);

        System.out.println(l.get(1).getK2());

        assertNotNull(l);


}

我收到一个错误,上面写着

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.ArrayList` out of START_OBJECT token
 at [Source: (String)"{
  "count": 30,
  "data": [
    {
      "k1": "v1",
      "k2": "v2"
    },
    {
      "k1": "no",
      "k2": "yes"
    }
  ]
}"; 

如何将数据数组反序列化为列表?

标签: javaspring-bootjacksonjackson-databind

解决方案


查看您的 json 数据,它是一个对象,但您试图将其解析为一个列表,您在 json 字符串中查找的列表存储在字段data中,因此请尝试这样的操作。

JSONObject json = new JSONObject(your_json_string);
JSONArray array = json.getJSONArray("data");

现在,您可以通过将array.toString()传递给对象映射器轻松获得所需的对象列表

谢谢


推荐阅读