反序列化具有键变量jackson map ObjectMapper的JSON

时间:2017-03-29 11:50:41

标签: android jackson mapper

JSON:

  {
    "id": "1704",
    "title": "Choice of Drink",
    "multiselect": 0,
    "maximum_selection": 1,
    "ac_items": 1,
    "Choice of Drink": [{
        "id": "8151",
        "name": "Lemon Ice Tea",
        "price": 0,
        "orig_price": 0
    }, {
        "id": "8152",
        "name": "Fresh Lime",
        "price": 0,
        "orig_price": 0
    }]
}

问题是关键的“饮料选择”是一个变量。当我没有这个名字时,我怎么能把它放在@JsonProperty中呢?

2 个答案:

答案 0 :(得分:0)

试试这个

 Gson gson = new Gson();
Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
Map<String,Map<String, String>> map = gson.fromJson(jsonString, mapType);

答案 1 :(得分:0)

您可以使用Jackson的@JsonAnySetter注释将所有变量键指向一个方法,然后您可以根据需要指定/处理它们:

public class Bar
{
    // known/fixed properties
    public String id;
    public String title;
    public int multiselect;
    public int maximum_selection;
    public int ac_items;

    // unknown/variable properties will go here
    @JsonAnySetter
    public void setDrinks(String key, Object value)
    {
        System.out.println("variable key = '" + key + "'");
        System.out.println("value is of type = " + value.getClass());
        System.out.println("value toString = '" + value.toString() + "'");
    }
}

在样本输入的情况下,输出为:

variable key = 'Choice of Drink'
value is of type = class java.util.ArrayList
value toString = '[{id=8151, name=Lemon Ice Tea, price=0, orig_price=0}, {id=8152, name=Fresh Lime, price=0, orig_price=0}]'