我有一个 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));
关于java - 在 json 文件中查找预定义架构属性的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40758977/