繁体   English   中英

解析具有未知结构以与已知结构进行比较的JSON的最佳方法?

[英]Best way to parse JSON with an unknown structure for comparison with a known structure?

我有一个YAML文件,我将其转换为JSON,然后使用GSON转换为Java对象。 这将用作我将比较其他YAML文件的标准定义。 我将要验证的YAML文件应包含与我的定义具有相同结构的字段。 但是,很有可能它可能包含结构不同的字段以及在我的定义中不存在的字段,因为最终要由用户在接收文件之前创建这些字段。 要验证的YAML中的字段看起来像这样,可以选择用户希望定义的嵌套级别。

 LBU:
      type: nodes.Compute
      properties:
        name: LBU
        description: LBU
        configurable_properties: 
          test: {"additional_configurable_properties":{"aaa":"1"}}
        vdu_profile:
          min_number_of_instances: 1
          max_number_of_instances: 4
      capabilities:
        virtual_compute:
          properties:
            virtual_memory:
              virtual_mem_size: 8096 MB
            virtual_cpu:
              cpu_architecture: x86
              num_virtual_cpu: 2
              virtual_cpu_clock: 1800 MHz
      requirements:
      - virtual_storage:
          capability: capabilities.VirtualStorage
          node: LBU_Storage        

当前,我收到此YAML文件,并使用Gson将其转换为JsonObject。 由于可能存在未知字段,因此无法将其映射到Java对象。 我的目标是遍历此文件,并针对我定义中匹配的每个字段验证每个字段。 如果存在定义中不存在的字段,或者存在但具有不同属性的字段,则需要向用户提供有关该字段的特定信息。

到目前为止,我正在走这样的领域。

 for (String field : obj.get("topology_template").getAsJsonObject().get("node_template").getAsJsonObject().get(key).getAsJsonObject().get(
              obj.get("topology_template").getAsJsonObject().get("node_templates").getAsJsonObject().get(key).getAsJsonObject().keySet().toArray()[i].toString()).getAsJsonObject().keySet()) {

但是,这似乎过于繁琐,并且对于某些深度嵌套的字段而言很难遵循。

我想知道的是,是否有一种更简单的方法来遍历JsonObject的每个字段,而无需将其映射到Java对象,也无需按名称显式访问每个字段?

我认为您正在寻找类似流Json Parser的东西:

这是一个例子

String json
  = "{\"name\":\"Tom\",\"age\":25,\"address\":[\"Poland\",\"5th avenue\"]}";
JsonFactory jfactory = new JsonFactory();
JsonParser jParser = jfactory.createParser(json);

String parsedName = null;
Integer parsedAge = null;
List<String> addresses = new LinkedList<>();

while (jParser.nextToken() != JsonToken.END_OBJECT) {
    String fieldname = jParser.getCurrentName();
    if ("name".equals(fieldname)) {
        jParser.nextToken();
        parsedName = jParser.getText();
    }

    if ("age".equals(fieldname)) {
        jParser.nextToken();
        parsedAge = jParser.getIntValue();
    }

    if ("address".equals(fieldname)) {
        jParser.nextToken();
        while (jParser.nextToken() != JsonToken.END_ARRAY) {
            addresses.add(jParser.getText());
        }
    }
}
jParser.close();

请在这里找到文档: https : //github.com/FasterXML/jackson-docs/wiki/JacksonStreamingApi

暂无
暂无

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

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