2016-11-17 49 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