给出类似的JSON:
{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}
如何选择b
,d
和e
以获取以下JSON?
{
"b":2,
"d":4,
"e":5
}
我想要一个JSON对象,而不只是2
,4
和5
值吗?
这就是我正在尝试和失败的原因:
$.[b,d,e]
答案 0 :(得分:2)
JSONPath不适合您要实现的目标:JSONPath旨在选择值而不是键值对。您可以使用Jackson或任何适用于Java的JSON解析器来实现您的目标。
如果你想在杰克逊这里找到能够解决问题的代码:
String json = "{\"a\":1,\"b\":2,\"c\":3,\"d\":4,\"e\":5}";
ObjectMapper mapper = new ObjectMapper();
JsonNode tree = mapper.readTree(json);
ObjectNode node = mapper.createObjectNode();
node.set("b", tree.get("b"));
node.set("d", tree.get("d"));
node.set("e", tree.get("e"));
String result = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
答案 1 :(得分:1)
你的json路径是正确的,而json
它自己不是。它应该是:
{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}
BTW为这些目的提供了良好的在线测试资源:http://jsonpath.com/
答案 2 :(得分:1)
元素必须用单引号引起来。
$.['b','d','e']
从com.jayway.jsonpath:json-path:2.4.0
对JsonPath正常工作答案 3 :(得分:0)
你需要修改你的JSON(如Andremoniy所说)
{
"a":1,
"b":2,
"c":3,
"d":4,
"e":5
}
并选择b,d,e使用此
$.b,d,e