我的目标是读取 JSON 文件并了解所有值的位置,以便当我遇到相同的 JSON 时,我可以轻松读取所有值。我正在寻找一种方法来返回包含每个数据值的所有路径的列表,在Jayway JsonPath format.
JSON 示例:
{
"shopper": {
"Id": "4973860941232342",
"Context": {
"CollapseOrderItems": false,
"IsTest": false
}
},
"SelfIdentifiersData": {
"SelfIdentifierData": [
{
"SelfIdentifierType": {
"SelfIdentifierType": "111"
}
},
{
"SelfIdentifierType": {
"SelfIdentifierType": "2222"
}
}
]
}
}
理想情况下,我想将该 JSON 作为字符串并执行如下操作:
String json = "{'shopper': {'Id': '4973860941232342', 'Context': {'CollapseOrderItems': false, 'IsTest': false } }, 'SelfIdentifiersData': {'SelfIdentifierData': [{'SelfIdentifierType': {'SelfIdentifierType': '111'} }, {'SelfIdentifierType': {'SelfIdentifierType': '2222'} } ] } }";
Configuration conf = Configuration.defaultConfiguration();
List<String> jsonPaths = JsonPath.using(conf).parse(json).read("$");
for (String path : jsonPaths) {
System.out.println(path);
}
此代码将打印以下内容,这是 JSON 中所有值的位置:
$.shopper.Id
$.shopper.Context.CollapseOrderItems
$.shopper.Context.IsTest
$.SelfIdentifiersData[0].SelfIdentifierData.SelfIdentifierType.SelfIdentifierType
$.SelfIdentifiersData[1].SelfIdentifierData.SelfIdentifierType.SelfIdentifierType
然后理想情况下,我将能够获取该列表并解析相同的 JSON 对象以获取每个值。
//after list is created
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
for (String path : jsonPaths) {
Object value = JsonPath.read(document, path);
//do something
}
我知道我可以获得一个表示 JSON 文件的 Map,但我不确定它能否提供同样轻松的访问来检索所有值。如果有一种简单的方法来使用 JSONPath,那就太好了,否则欢迎任何其他方法。