如何将Json属性名称映射到Java字段值

时间:2013-05-22 15:15:23

标签: java json jackson

如何使用jackson将JSON属性名称映射到Java字段值?

此:

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

到此:

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

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

片段"monday":[ "apple", "bread"]映射到两个变量,一个具有属性名称,另一个具有属性值。

2 个答案:

答案 0 :(得分:1)

您的JSON表示简单的地图列表,更准确地说是:List<Map<String, List<String>>>。您可以将此JSON转换为此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;
    }
}

现在我们可以用这种方式反序列化JSON:

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());
}

计划的输出:

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

答案 1 :(得分:0)

使用注释@JsonProperty如果要更改名称,请使用带参数的注释,例如@JsonProperty("stuff_name")