在 json 文件中查找预定义架构属性的最佳方法

Best way to find the pre-defined schema properties in a json file

我有一个 json 架构文件,它遵循我创建的自定义规则。此架构文件是有效的 json 文件。它遵循以下模式。

 {
    "name":   {
                "fname" :  {
                             "displayName":"FirstName",
                             "dataType":"String"
                           }
                "lname"  : {
                             "displayName":"LastName",
                             "dataType":"String"
                           }
               },
    "address": {
                   "displayName":"Address",
                   "dataType":"String"
               }
  }

因此,根据架构,我需要使用各自的值创建以下 json。

  {
       "name": {
                 "FirstName": "test",
                 "LastName" : "test1"
               },
       "Address" : "someAddress"
  }

所以当我得到架构时,找到配置信息节点的最佳方法是什么?这是具有 displayName 和 dataType 参数的叶节点。目前我正在使用 Jackson json 遍历这棵树并找到带有 displayName 和 dataType 键的节点。因为我不能准确地说出这个叶节点可能存在于哪个级别。有没有比遍历整个 json 树寻找元素更好的方法来处理这种情况?

我不确定是否需要 wnat(您想要 fname 对象还是它的属性值),但是,JsonPath 似乎很适合这里。它相当于 json 的 xpath - 基于各种条件的搜索层次模型

我制作了一个小演示来帮助您入门。您只需要调整查询字符串以满足您的要求。您可以使用 Jayway JsonPath Evaluator 作为 REPL

import java.nio.file.*;
import com.jayway.jsonpath.*;
public class JsonPathDemo
{
    public static void main(String[] args)
    {
        // query: get all json objects that have displayName and dataType properties
        String jsonPathQuery = "$..*[?(@.displayName && @.dataType)]";
        try {
            String content = new String(Files.readAllBytes(Paths.get("C://temp/xx.json")));
            Object parsedContent = Configuration.defaultConfiguration().jsonProvider().parse(content);
            Object configElements = JsonPath.read(parsedContent, jsonPathQuery);
            System.out.println(configElements.getClass());
            System.out.println(configElements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 

输出为

class net.minidev.json.JSONArray
[{"displayName":"Address","dataType":"String"},{"displayName":"FirstName","dataType":"String"},{"displayName":"LastName","dataType":"String"}]

编辑: 评论中问题的回答:

可以使用 json-path-assert:

检查路径是否存在(并做出各种其他断言)
import static com.jayway.jsonpath.matchers.JsonPathMatchers.*;

// query for specific path 
String jsonSpecificPathQuery = "$..name.fname.displayName";

String content = new String(Files.readAllBytes(Paths.get("C://temp/xx.json")));
Object parsedContent = Configuration.defaultConfiguration().jsonProvider().parse(content);
System.out.println("hasJsonPath? " + hasJsonPath(jsonSpecificPathQuery).matches(parsedContent));