user1475578
user1475578

Reputation:

How to map a Json attribute name to a Java field value

How to map a JSON attribute name to Java field value using jackson?

This:

{ "list":[  { "monday":[ "apple", "bread"] } ,
            { "sunday":[ "bacon", "beer" ] } ],
  "kind":"shoplist" }

to this:

public class StuffList {
    public List<Stuff> list;
    public String kind;
}

public class Stuff {
    public String name;
    public List<String> items; 
}

The fragment "monday":[ "apple", "bread"] is mapped to two variables, one with the attribute name and another with the attribute value.

Upvotes: 1

Views: 5647

Answers (2)

Michał Ziober
Michał Ziober

Reputation: 38625

Your JSON represets simple list of maps, more exactly: List<Map<String, List<String>>>. You can convert this JSON into this POJO:

class JsonEntity {

    public List<Map<String, List<String>>> list;
    public String kind;

    public StuffList toStuffList() {
        StuffList stuffList = createStuffListObject();

        return stuffList;
    }

    private StuffList createStuffListObject() {
        StuffList stuffList = new StuffList();
        stuffList.kind = kind;
        stuffList.list = createItemsList();

        return stuffList;
    }

    private List<Stuff> createItemsList() {
        List<Stuff> items = new ArrayList<Stuff>(list.size());
        for (Map<String, List<String>> item : list) {
            items.add(convertToStuff(item));
        }

        return items;
    }

    private Stuff convertToStuff(Map<String, List<String>> item) {
        Stuff stuff = new Stuff();
        stuff.name = item.keySet().iterator().next();
        stuff.items = item.values().iterator().next();

        return stuff;
    }
}

And now we can deserialize JSON in this way:

public static void main(String[] args) throws Exception {
    String json = "{\"list\":[{\"monday\":[\"apple\", \"bread\"]},{\"sunday\":[\"bacon\", \"beer\"]} ],\"kind\":\"shoplist\"}";

    ObjectMapper objectMapper = new ObjectMapper();
    JsonEntity jsonEntity = objectMapper.readValue(json, JsonEntity.class);
    System.out.println(jsonEntity.toStuffList());
}

Output of the program:

list=[[name=monday, items=[apple, bread]], [name=sunday, items=[bacon, beer]]], kind=shoplist

Upvotes: 1

AlexR
AlexR

Reputation: 115328

Use annotation @JsonProperty If you want to change name use annotation with argument, e.g. @JsonProperty("stuff_name")

Upvotes: 1

Related Questions