【问题标题】:Parse JSON with JsonArray and HashMap使用 JsonArray 和 HashMap 解析 JSON
【发布时间】: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?

谢谢

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

    寻找这个链接,有一个专门为你准备的演示应用程序:https://github.com/nalmelune/jackson-demo-58591850(看JacksonTest

    首先,您需要为此的数据类(或所谓的dto),表示结构。您可以为此使用在线生成器(谷歌“json to java dto online”)或自己做。例如,这里是根对象(更多信息请参见 github 链接):

    public class Root {
       private int totalCount;
       private List<Results> results;
    
       public void setTotalCount(int totalCount) {
           this.totalCount = totalCount;
       }
    
       public int getTotalCount() {
           return this.totalCount;
       }
    
       public void setResults(List<Results> results) {
           this.results = results;
       }
    
       public List<Results> getResults() {
           return this.results;
       }
    }
    

    然后配置你的 ObjectMapper:

    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JavaTimeModule());
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    

    并使用它(不要创建新的映射器,就像在您的示例中那样):

    Root result = mapper.readValue(response, Root.class);
    

    最后,你可以像往常一样访问Plain Old Java Objects:

        for (Results resultItem : result.getResults()) {
            System.out.println(resultItem.getSalutation());
            System.out.println(resultItem.getName());
            System.out.println(resultItem.getZipCodeCity());
            System.out.println(resultItem.getOpeningDate());
            System.out.println(resultItem.getStreetHouseNumber());
        }
    

    为了使其正常工作,请务必验证您的 json(“范围”后有无效逗号,“名称”出现两次,依此类推,已在 github 上修复)。并确保通过添加com.fasterxml.jackson.datatype:jackson-datatype-jsr310 模块在类路径中包含jsr310LocalDateLocalDateTime 对象将需要它。

    【讨论】:

    • 非常感谢,我迫不及待想试一试!
    【解决方案2】:

    你可以创建类似下面的 java 类

    @Data
     class MyCustomClass{
        int totalCount;
        List<TeleCommunicationDetail> results;
       // other props
     }
    

    接下来你可以给 TeleCommunicationDetail 添加属性,最后你可以使用MyCustomClass reaonseInJavaObject = objectMapper.readValue(myJson,MyCustomClass.class);

    详情请参考this问题。

    【讨论】:

      【解决方案3】:

      您的方法是正确的,因为您只需将 JSON 对象读取为Map&lt;String, Object&gt;,它始终可以工作(只要 JSON 对象有效)。然后你检索你期望在那里的价值观。另一种方法是创建一个映射到原始 JSON 的类,并将带有 ObjectMapper 的 JSON 解析到您的类中。然后你可以用你的类设置器和获取器来检索你的数据。在这种情况下,您不需要使用“结果”等关键字符串,但您必须确保您的 JSON 不仅是有效的 JSON,而且始终符合您的类。选择你的选项...

      【讨论】:

        猜你喜欢
        • 2017-08-13
        • 2012-04-18
        • 1970-01-01
        • 1970-01-01
        • 2017-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多