简体   繁体   中英

Convert Json Containing Map of similar list into POJO

I need to convert following response into 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'.

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

{ "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.

Example example = objectmapper.readValue(responseBody,Example.class);

A simple Map<List<Item>> would work:

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:

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:

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM