如何反序列化JSON数组以列出?

时间:2018-12-26 10:28:44

标签: java spring-boot jackson jackson-databind

我正在尝试使用jackson使用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"
    }
  ]
}"; 

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

3 个答案:

答案 0 :(得分:2)

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

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

现在,您可以通过将 array.toString()传递给对象映射器

轻松获得所需的对象列表

谢谢

答案 1 :(得分:0)

如果您使用的是GSON库,则该方法应该起作用:

  Type type = new TypeToken<List<KeyValueModel>>(){}.getType();
  List<KeyValueModel> l = new Gson().fromJson(jsonList,type);

答案 2 :(得分:0)

您需要再创建一个类,因为json字符串中还有一个属性计数

public class Test{

    private String count;
    private KeyValueModel[] kv;

}

然后将代码更改为

Test test = mapper.readValue(jsonList, Test.class);
System.out.println(test.getKv()[0].getK1()) will get the expected result