简体   繁体   English

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

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

I have a YAML file which I convert to JSON, and then to a Java object using GSON . 我有一个YAML文件,我将其转换为JSON,然后使用GSON转换为Java对象。 This will be used as the standard definition which I will compare other YAML files against. 这将用作我将比较其他YAML文件的标准定义。 The YAML files which I will be validating should contain fields with identical structures to my definition. 我将要验证的YAML文件应包含与我的定义具有相同结构的字段。 However, it is very possible that it might contain fields with different structure, and fields that don't exist within my definition, as it is ultimately up to the user to create these fields before I receive the file. 但是,很有可能它可能包含结构不同的字段以及在我的定义中不存在的字段,因为最终要由用户在接收文件之前创建这些字段。 A field in the YAML to be validated can look like this, with the option of as many levels of nesting as the user wishes to define. 要验证的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        

Currently, I receive this YAML file and convert it to a JsonObject with Gson. 当前,我收到此YAML文件,并使用Gson将其转换为JsonObject。 It is not possible to map this to a Java object because of any possible unknown fields. 由于可能存在未知字段,因此无法将其映射到Java对象。 My goal is to run through this file and validate every single field against a matching one in my definition. 我的目标是遍历此文件,并针对我定义中匹配的每个字段验证每个字段。 If a field is present that does not exist in the definition, or does exist but has properties that differ, I need to inform the user with specific info about the field. 如果存在定义中不存在的字段,或者存在但具有不同属性的字段,则需要向用户提供有关该字段的特定信息。

So far, I am going the route of getting fields like this. 到目前为止,我正在走这样的领域。

 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()) {

However, it seems that this is rather excessive and is very hard to follow for some deeply nested fields. 但是,这似乎过于繁琐,并且对于某些深度嵌套的字段而言很难遵循。

What I want to know is if there is a simpler way to traverse every field of a JsonObject, without mapping it to a Java object, and without explicitly accessing each field by name? 我想知道的是,是否有一种更简单的方法来遍历JsonObject的每个字段,而无需将其映射到Java对象,也无需按名称显式访问每个字段?

I think you are looking for something like a streaming Json Parser: 我认为您正在寻找类似流Json Parser的东西:

Here's an example 这是一个例子

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();

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

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

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