简体   繁体   English

在Java中解析Json对象中动态名称的最佳方法是什么?

[英]What is the best way to parse dynamic names in Json objects in Java?

I would prefer to use com.fasterxml.jackson if that possible. 如果可能的话,我宁愿使用com.fasterxml.jackson。 I'm looking for a way to parse json like this: 我正在寻找一种解析json的方法,如下所示:

{
   "availability":{
      "48":{              //this is dynamic (in next response that number can be different, like 1023)
         "2018-02-08":{   //this is dynamic
            "temp":null
         },
         "2018-02-09":{   //this is dynamic
            "temp":null
         }
      },
      "49":{              //this is dynamic
         "2018-02-08":{   //this is dynamic
            "temp":null
         },
         "2018-02-09":{   //this is dynamic
            "temp":null
         }
      }
   }
}

You can use GSON by google: 您可以通过Google使用GSON:

        import com.google.gson.Gson;
        import com.google.gson.JsonArray;
        import com.google.gson.JsonElement;

        HttpClient httpClient = httpClientIgnoreCertificates();
        HttpGet get = new HttpGet(uri);
        HttpResponse response;
        String responseEntity = null;
        try {
             response = httpClient.execute(get);
             responseEntity = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
        } catch (IOException e) {
                    e.printStackTrace();
        }
        JsonArray jsonObjects = new Gson().fromJson(responseEntity, 
        JsonArray.class);
        JsonArray items =
   jsonObjects.get(0).getAsJsonObject().get("availability").getAsJsonArray();

And than you can do actions with your jsonArray.. 然后您可以使用jsonArray进行操作。

Two ways to do it in fasterxml Jackson. 在fasterxml Jackson中,有两种方法可以做到这一点。

  1. Try using the JSON Tree model 尝试使用JSON树模型

The Api JsonNode takes care of converting the input String to a parsable Json Object. Api JsonNode负责将输入的String转换为可解析的Json对象。 you can find the tutorials to use them in the following links Baeldung's Site , and API details are in this link 您可以在以下链接中找到要使用的教程Baeldung的Site ,并且API详细信息在此链接中

I tried running your example here, PFB the debug screenshot... 我尝试在此处运行示例,PFB调试屏幕截图...

IntelliJIDEA的DebugScreenshot

  1. Try the Json Object Model as detailed in this Dzone Link 试试这个Dzone链接中详细介绍的Json对象模型

At the class level add annotation @JsonInclude(JsonInclude.Include.NON_NULL) this will exclude any elements which are null when doing un-marshalling to the corresponding domain object 在类级别添加注释@JsonInclude(JsonInclude.Include.NON_NULL)这将排除对相应域对象进行解编组时为null的所有元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM