How to read deep hierarchical JSON format with JsonNode class and readTree method in Java library jackson
If you do not know what format the JSON format comes in, use the readTree method to obtain a JsonNode object.
This JsonNode object can be used to manipulate arbitrary JSON objects.
Specify key as the argument of the get method. The result is returned as value.
The JSON of a String string is assumed to be the following.
{ "key1":{ "id":20, "name":"takahashi" }, "key2":["val1", "val2"] }
Using the JsonNode class, it is easy to obtain deep hierarchical values, such as the id of key1.
package jp.co.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class SampleJackson3 { private static ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args) throws JsonProcessingException { String json = "{\"key1\":{\"id\":20,\"name\":\"takahashi\"},\"key2\":[\"val1\",\"val2\"]}"; JsonNode node = mapper.readTree(json); System.out.println(node.toString());// Get the entire JSON as a string System.out.println(node.get("key1").get("id")); System.out.println(node.get("key1").get("name")); System.out.println(node.get("key2")); } }
The readTree method is passed a string type in JSON format; a JsonNode object is returned, and the toString() method returns the entire JSON as a string.
Passing a key to the get method returns value. The result is as follows
{"key1":{"id":20,"name":"takahashi"},"key2":["val1","val2"]} 20 "takahashi" ["val1","val2"]
If an array in JSON format is returned, it can be looped through with a for statement.
JsonNode provides a size() method.
package jp.co.jackson; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; public class SampleJackson3 { private static ObjectMapper mapper = new ObjectMapper(); public static void main(String[] args) throws JsonProcessingException { String json = "{\"key1\":{\"id\":20,\"name\":\"takahashi\"},\"key2\":[\"val1\",\"val2\"]}"; JsonNode node = mapper.readTree(json); JsonNode obj = node.get("key2"); for(int i = 0;i<obj.size();i++) { System.out.println(obj.get(i)); } } }
The result shows that the following arrays can be processed sequentially.
"val1" "val2"
コメント