【发布时间】:2019-10-28 13:30:49
【问题描述】:
我需要解析以下 JSON 并将其中的值添加到三个不同的 Java 对象中。为了做到这一点,我正在考虑组建其他 3 个 Json。我有一些解析问题,因为 JSON 有点复杂。 JSON如下:
{
"totalCount": 1,
"results": [
{
"teleCommunications": [
{
"areaCode": "100",
"telephoneNumber": "300-2444",
"internationalAreaCode": "",
"communicationType": 1
},
{
"areaCode": "100",
"telephoneNumber": "200-2555",
"internationalAreaCode": "",
"communicationType": 5
}
],
"delegate": {
"id": 0,
"range": 0,
},
"name": "Andrew",
"composedKey": {
"id": 615,
"range": 50,
},
"isBranchAddress": false,
"emailAddresses": [
{
"emailAddressType": 9,
"emailAddress": "andrew.brown@gmail.com"
}
],
"name": "Brown",
"zipCodeCity": "65760 Leipzig",
"salutation": "Mr.",
"openingDate": "2019-09-20",
"streetHouseNumber": "Offenbach. 37",
"modificationTimestamp": "2018-01-27"
}
]
}
我需要分别从 JSON(或任何其他方式)中的 name、zipCodeCity、salutation、openingDate、streetHouseNumber、不同 JSON 中的 emailAddresses 和另一个 JSON 中的其他数据中获取值。
我试过这段代码:
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
HashMap<String, Object> result = new ObjectMapper().readValue(response, HashMap.class);
Object object = result.get("results");
List<HashMap<String, String>> jsonValues = (List<HashMap<String, String>>)object;
for(String key : jsonValues.get(0).keySet()){
System.out.println("name value " + jsonValues.get(0).get("name"));
System.out.println("zip code City " + jsonValues.get(0).get("zipCodeCity"));
}
问题是我不会采用这种硬编码的方式……它不是很合适。 有谁知道更好的方法来存储我需要的值并更优化地解析 Json?
谢谢
【问题讨论】: