Java 如何将JSON数组反序列化为列表?
我正在尝试使用jackson使用JSON 我想要绑定json的类是:- KeyValueModel.classJava 如何将JSON数组反序列化为列表?,java,spring-boot,jackson,jackson-databind,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 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);
}
如何将数据数组反序列化到列表中?查看您的json数据,它是一个对象,但您正试图将其解析为列表,您在json字符串中查找的列表存储在字段data,请尝试类似的操作
JSONObject json = new JSONObject(your_json_string);
JSONArray array = json.getJSONArray("data");
现在,通过将array.toString()传递到对象映射器,您可以轻松获得所需的对象列表
感谢查看您的json数据,它是一个对象,但您正试图将其解析为一个列表,您在json字符串中查找的列表存储在字段data,请尝试类似的操作
JSONObject json = new JSONObject(your_json_string);
JSONArray array = json.getJSONArray("data");
现在,通过将array.toString()传递到对象映射器,您可以轻松获得所需的对象列表
谢谢如果您正在使用GSON库,这应该可以:
Type type = new TypeToken<List<KeyValueModel>>(){}.getType();
List<KeyValueModel> l = new Gson().fromJson(jsonList,type);
Type Type=new-TypeToken(){}.getType();
List l=new Gson().fromJson(jsonList,type);
如果您使用的是GSON库,这应该可以:
Type type = new TypeToken<List<KeyValueModel>>(){}.getType();
List<KeyValueModel> l = new Gson().fromJson(jsonList,type);
Type Type=new-TypeToken(){}.getType();
List l=new Gson().fromJson(jsonList,type);
您需要再创建一个类,因为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
您需要再创建一个类,因为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