反序列化具有键变量 jackson map ObjectMapper 的 JSON
Deserialize a JSON that has a key variable jackson map ObjectMapper
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
}]
}
问题是键 "Choice of Drink" 是一个 variable.How,当我没有名称时,我可以将它放在 @JsonProperty 中吗?
试试这个
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
Map<String,Map<String, String>> map = gson.fromJson(jsonString, mapType);
您可以使用 Jackson 的 @JsonAnySetter
注释将所有变量键指向一个方法,然后您可以根据需要 assign/handle 它们:
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}]'
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
}]
}
问题是键 "Choice of Drink" 是一个 variable.How,当我没有名称时,我可以将它放在 @JsonProperty 中吗?
试试这个
Gson gson = new Gson();
Type mapType = new TypeToken<Map<String,Map<String, String>>>() {}.getType();
Map<String,Map<String, String>> map = gson.fromJson(jsonString, mapType);
您可以使用 Jackson 的 @JsonAnySetter
注释将所有变量键指向一个方法,然后您可以根据需要 assign/handle 它们:
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}]'