I have a JsonNode with the structure:
{
'field1': 'value1'
'field2': 'value2'
}
I want to retrieve 'value1'
by specifying a json path: "$.field1"
. However, instead of getting 'value1'
, I'm getting the path itself. See the following illustration:
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']"]
Why am I getting ["$['field1']"]
? It looks like it just normalized the path..
I'm not sure that the JSON that you gave is correct as it contains single quotes for key and value.
Your JSON is not a valid JSON. JSON only allows double quotes for key and value.
Valid JSON should be like this:
{
"field1": "value1",
"field2": "value2"
}
Your code I have tested by modifying a little bit:
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("{\"field1\": \"value1\"," + "\"field2\": \"value2\"}");
Object value = context.read(path);
System.out.println(value);
}
}
Output:
value1
Please check the string value that is coming from JsonNode.toString()
by debugging.
Your jsonNode.toString()
should return something this:
"{\"field1\": \"value1\"," + "\"field2\": \"value2\"}"
I'm 100% sure that you are not getting this string from JsonNode when passed to parse method.