2017-03-29 4 views
0

JSON을 주요 변수 잭슨지도 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 
    }] 
} 

문제는 키 "음료의 선택"은 variable.How, 나는이 @JsonProperty이 넣을 수 있다는 것이다 때 이름이 없니?

+0

가변적 인 문자열 값 목록이 있습니까 할 수 있을까요? Choice of Drink가 그 중 하나입니다. –

+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

Jackson을 사용하십시오. –