我有一个具有以下结构的 JsonNode:
{
'field1': 'value1'
'field2': 'value2'
}
我想通过指定json路径来检索
'value1'
:"$.field1"
。然而,我得到的是路径本身,而不是'value1'
。见下图:
JsonNode node = ...
String path = "$.field1";
Configuration conf = Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
ReadContext context = JsonPath.using(conf).parse(jsonNode.toString());
Object value = context.read(path);
System.out.println(value);
// Output: ["$['field1']"]
为什么我会得到
["$['field1']"]
?看起来它只是标准化了路径..
我不确定您提供的 JSON 是否正确,因为它包含键和值的单引号。
您的 JSON 不是验证 JSON。 JSON 只允许键和值使用双引号。
验证 JSON 应该是这样的:
{
"field1": "value1",
"field2": "value2"
}
你的代码我已经通过修改一点点进行了测试:
public class Example {
public static void main(String args[]) throws Exception {
String path = "$.field1";
Configuration conf = Configuration.defaultConfiguration().addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL);
ReadContext context = JsonPath.using(conf).parse("{\n" +
"\"field1\": \"value1\",\n" +
"\"field2\": \"value2\"\n" +
"}");
Object value = context.read(path);
System.out.println(value);
}
}
输出:
value1
请通过调试检查来自
JsonNode.toString()
的字符串值。