I have the following json file test.json
{
"type" : "object",
"id" : "123",
"title" : "Test",
"properties" : {
"_picnic" : {
"type" : "boolean"
....
I am able to get the first level value of the key using the following code. E.g. for type
I get object
public static void main(String[] args){
String exampleRequest = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
exampleRequest = FileUtils.readFileToString(new File("src/main/resources/test.json"), StandardCharsets.UTF_8);
JsonNode jsonNode = objectMapper.readTree(exampleRequest);
String type = jsonNode.get("type").asText();
System.out.println(type);
} catch (IOException e) {
throw new RuntimeException(e);
}
// System.out.println(exampleRequest);
}
However I do not get any response when I try to get the value for the second level. E.g. if I do
String type = jsonNode.get("_picnic").asText();
System.out.println(type);
OR the whole object e.g.
String type = jsonNode.get("properties").asText();
System.out.println(type);
I tried doing properties._picnic
or properties[0]_picnic
but no luck.
2
Answers
The documentation for that method states (emphasis mine):
Per the snippet of json text you shared, both
"properties"
and"_picnic"
are objects not values so you are getting an empty string. It seems you’d need to use the get method:You can use recursion to simplify this code. Just call
getText
with a starting node and a variable list (array) of paths. It will determine if it need to check for object or array.Modified
test.json
: