java - 如何反序列化 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"
}
]
}";
如何将数据数组反序列化为列表?
解决方案
查看您的 json 数据,它是一个对象,但您试图将其解析为一个列表,您在 json 字符串中查找的列表存储在字段data中,因此请尝试这样的操作。
JSONObject json = new JSONObject(your_json_string);
JSONArray array = json.getJSONArray("data");
现在,您可以通过将array.toString()传递给对象映射器轻松获得所需的对象列表
谢谢
推荐阅读
- java - Spring Boot 查询构建器机制如何工作?(Crud 存储库)
- c++ - 输入验证以过滤掉字符、字符串和一系列整数
- linux - 是否可以在远程服务器上运行 Netlogo?
- javascript - 使用 fetch api 上传文件 & 获取文件上传数据
- javascript - 在 Sweetalert 显示成功的消息通知
- tensorflow - 无法转换“图像”:预期为 float32,得到“省略号”类型的省略号
- ruby-on-rails - 为什么 ActiveModel::Errors.new(self) 不适用于长度,而是使用计数和大小方法?
- sql-server - 如何在 SQL Server 中使用多个更新查询
- python - 当菜单使用输入时从下拉菜单中选择一个项目,而不是选择
- php - 使用foreach拆分字符串?