1

如何使用杰克逊将 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"]映射到两个变量,一个带有属性名称,另一个带有属性值。

4

2 回答 2

1

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

于 2013-05-22T15:19:32.330 回答
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
于 2013-05-23T21:07:19.767 回答