[英]Convert Json Containing Map of similar list into POJO
I need to convert following response into POJO 我需要将以下响应转换为POJO
{
"abc" : [
{
"a" : "",
"b": "",
"c" : ""
},
{
"a" : "",
"b": "",
"c" : ""
}
],
"xyz" : [
{
"a" : "",
"b": "",
"c" : ""
},
{
"a" : "",
"b": "",
"c" : ""
}]
}
For inside object i have a class lets call it 'A'. 对于内部对象,我有一个类可以称之为“ A”。
public class A{
private string a;
private string b;
private string c;
constructor..
getter..
setter..
}
My json contains many objects like "acb" and "xyz" ie list of same object type 'A' and keys for the same is not known for eg 我的json包含许多对象,例如“ acb”和“ xyz”,即,相同对象类型“ A”的列表以及该对象的键例如不为人知
{ "abc" [---],
"def" [---],
"ghi" [---],
"jkl" [---],
.......
"xyz" [---]
}
I have tried Using following class for the same 我已经尝试过使用以下课程
Public class Example{
Map<String,List<A>> response;
public Example(Map<String,List<A>> response){
this.response = response;
}
getter...
setter...
}
it does not seems to be working, I am using Object Mapper class to convert. 它似乎不起作用,我正在使用Object Mapper类进行转换。
Example example = objectmapper.readValue(responseBody,Example.class);
A simple Map<List<Item>>
would work: 一个简单的Map<List<Item>>
可以工作:
class Item{
private String a="";
private String b="";
private String c="";
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public String getC() {
return c;
}
public void setC(String c) {
this.c = c;
}
}
To create the json: 要创建json:
List<Item> list = new ArrayList<Item>();
list.add(new Item());
list.add(new Item());
List<Item> list2 = new ArrayList<Item>();
list2.add(new Item());
list2.add(new Item());
Map<String,List<Item>> map = new HashMap<String,List<Item>>();
map.put("abc", list);
map.put("xyz", list);
ObjectMapper objectMapper = new ObjectMapper();
String writeValueAsString = objectMapper.writeValueAsString(map);
The reverse to load the json into a map: 将json加载到地图中的相反操作:
String json = "{\"abc\":[{\"a\":\"val\",\"b\":\"val\",\"c\":\"val\"},{\"a\":\"val\",\"b\":\"val\",\"c\":\"val\"}],\"xyz\":[{\"a\":\"val\",\"b\":\"val\",\"c\":\"val\"},{\"a\":\"val\",\"b\":\"val\",\"c\":\"val\"}]}";
Map<String,List<Item>> map = objectMapper.readValue(json, Map.class);
So, in the end, it's very similar to what you had. 因此,最后,它与您所拥有的非常相似。 It's simply the extra level of 'Example' that was causing you trouble... 仅仅是“示例”的额外级别给您带来麻烦...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.