所以我一直在用jayway JSONPath像下面这样查询 JSON 对象:
{
"messageHeader" : {
"sentBy" : "someOne",
"userName" : "John Doe"
},
"payload" : []
}
这在大多数情况下工作正常,除了现在我希望使用路径 $..* 选择根级对象并根据消息中存在的对象类型使用它们的键/名称执行单独的任务作为标识符。 但是,使用上述路径或 $.* ,将始终生成一个 JSONArray,就像这样:
[{sentBy:someOne,userName:John Doe},[]]
JSON 对象似乎是匿名的,它们没有 key 。无论如何我可以直接将这些对象的键作为字符串访问吗?如果数据不存在,那么为什么路径: $.messageHeader.sentBy 有效?
最佳答案
来自 README JsonPath 的:
When evaluating a path you need to understand the concept of when a path is definite. A path is indefinite if it contains:
- .. - a deep scan operator
- ?() - an expression
- [, (, )] - multiple array indexes
Indefinite paths always returns a list (as represented by current JsonProvider).
这应该可以解释上述现象。
关于java - 如何使用 JSONPath 获取根级别 JSON 对象的键/名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30878199/