【发布时间】:2016-01-18 08:50:53
【问题描述】:
我的目标是读取 JSON 文件并了解所有值的位置,这样当我遇到相同的 JSON 时,我可以轻松读取所有值。我正在寻找一种方法以Jayway JsonPath 格式返回包含每个数据值的所有路径的列表。
示例 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,那就太好了,否则欢迎任何其他方法。
【问题讨论】:
-
使用任何 json 解析和一点递归,看起来并不复杂
标签: java json hashmap jsonpath