我的目标是读取JSON文件并理解所有值的位置,以便当我遇到相同的JSON时,可以轻松读取所有值。我正在寻找一种方法来返回一个列表,其中包含所有到每个数据值的路径,格式为Jayway JsonPath。如何从JSON字符串中获取所有JSON路径的值列表?
例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
那么理想情况下,我将能够获取该列表并解析th使用相同的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文件的表示,但我不知道提供相同四通八达的交通网络,以获取所有值。如果使用JSONPath有一个简单的方法,那很好,否则任何其他方法都是可以的。
使用任何json解析和一点递归它似乎不是很复杂 – njzk2