2017-03-29 16 views
0

JSON一個JSON:反序列化,有一個關鍵變量 - 傑克遜地圖ObjectMapper

{ 
    "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 
    }] 
} 

的問題是關鍵「飲料的選擇」是variable.How我可以把這個在@JsonProperty,當我沒有名字?

+0

是否有一個固定的字符串值列表,該變量可能需要?飲料的選擇就是其中之一。 –

+0

讓傑克遜把動態密鑰解析成一個'Map >'。 – nbokmans

+0

@AishwaryaTiwari不,樣本中不固定 –

回答

0

您可以使用傑克遜@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}]' 
+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); 
+0

請使用傑克遜。 –