【问题标题】:What is the best way to parse dynamic names in Json objects in Java?在 Java 中解析 Json 对象中的动态名称的最佳方法是什么?
【发布时间】:2018-07-23 14:17:48
【问题描述】:

如果可能的话,我更愿意使用 com.fasterxml.jackson。 我正在寻找一种像这样解析 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
         }
      }
   }
}

【问题讨论】:

  • 简单地将动态数据表示为Map
  • 动态是什么意思?
  • 到目前为止你尝试过什么?还有哪些解析器喜欢snakeyaml?

标签: java json dynamic fasterxml


【解决方案1】:

您可以通过 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();

而且你可以用你的 jsonArray.. 做一些动作。

【讨论】:

    【解决方案2】:

    在 fastxml Jackson 中有两种方法。

    1. 尝试使用 JSON 树模型

    Api JsonNode 负责将输入字符串转换为可解析的 Json 对象。您可以在以下链接中找到使用它们的教程Baeldung's Site,API 详细信息在this link

    我尝试在这里运行您的示例,PFB 调试屏幕截图...

    1. 尝试使用此Dzone Link 中详细介绍的 Json 对象模型

    在类级别添加注解@JsonInclude(JsonInclude.Include.NON_NULL) 这将在对相应的域对象进行解编组时排除任何为空的元素

    【讨论】:

    • 抱歉,动态,我的意思是每次通话的名称都会不同,所以如果我再打一个电话,49 可以是 109
    • 嗨 Michal,我假设您的应用程序将有一个模块/方法,它将返回要获取的密钥。例如,必要的键必须是 49 还是 149。无论哪种方式,让我们说要获取的键是 String str。您仍然可以在 str 上执行 findValue。在这种情况下,只有第 1 点的解决方案是可能的..
    猜你喜欢
    • 2017-05-24
    • 2022-01-06
    • 2019-09-16
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-25
    • 1970-01-01
    • 2010-11-08
    相关资源
    最近更新 更多