2016-11-17 51 views
-2

我必須創建以下JSON的POJO類,問題是鍵p_d具有像s_t,n_t,n_p等動態名稱的變量。真正的JSON很大,我是隻與該部分面臨問題,我分享了部分JSON。 我正在使用jackson解析。JSON到動態鍵值對的JAVA POJO

{ 
    "flag": true, 
    "flag2": false, 
    "r_no": [ 
    { 
     "room_type": 250067, 
     "no_of_rooms": 1, 
     "no_of_children": 1, 
     "no_of_adults": 2, 
     "description": "Executive Room, 1 King Bed, Non Smoking", 
     "children_ages": [ 
     8 
     ] 
    }, 
    { 
     "room_type": 250067, 
     "no_of_rooms": 1, 
     "no_of_children": 0, 
     "no_of_adults": 2, 
     "description": "Executive Room, 1 King Bed, Non Smoking" 
    } 
    ], 
    "r_code": "abc", 
    "r_key": "123", 
    "p_d": { 
    "s_t": [ 
     { 
     "name": "xyz", 
     "cur": "INR" 
     }, 
     { 
     "name": "xyz1", 
     "cur": "INR" 
     } 
    ], 
    "n_t": [ 
     { 
     "name": "xyz2", 
     "cur": "INR" 
     } 
    ], 
    "n_p": [ 
     { 
     "name": "xyz5", 
     "cur": "INR" 
     } 
    ] 
    }, 
    "cur": "INR" 
} 
+0

哪裏是你try代碼? @Suraj –

+0

public class PD { @JsonProperty(「s_t」) private List sT = new ArrayList (); @JsonProperty(「n_t」) private列表 nT = new ArrayList (); @JsonProperty(「n_p」) private列表 nP = new ArrayList (); @JsonIgnore private Map additionalProperties = new HashMap (); setter getter} – Suraj

+0

這裏的變量名稱是靜態的,但需要動態變量。 – Suraj

回答

3

對於動態密鑰,使用Map<String, Object>

ObjectMapper mapper = new ObjectMapper(); 
Map<String, Object> parsed = mapper.readValue(json, 
            new TypeReference<Map<String, Object>>() {}); 
+0

做同樣的事情,但是JSON很大,我只共享我正面臨的問題ObjectMapper mapper = new ObjectMapper(); \t \t嘗試{ \t \t \t responseDto = mapper.readValue(response,com.HSR.class); (JsonGenerationException e){ \t \t} catch(JsonGenerationException e){ \t \t \t e.printStackTrace(); \t \t} – Suraj