Reading json data in non-streaming way (object model)

We can read a json file and create an object model of it, using the ObjectMapper’s readTree api.

ObjectMapper class is responsible for parsing the json file and create appropriate java objects. It uses Jackson’s parsing feature internally for reading the json file.

They are many overloaded method of readTree available in ObjectMapper. In this example I will be using the api which accepts the File object as a parameter and returns an instance of JsonNode class as shown in line 17 of below code.

JsonNode is an abstract super class and its subclasses are used to represents different nodes in json file.

Below is an example of reading json file and creating an object model of it.

Main Code


1  package package10;
2  
3  import java.io.File;
4  import java.io.IOException;
5  import java.util.Iterator;
6  import java.util.Map;
7  import java.util.Map.Entry;
8  
9  import com.fasterxml.jackson.core.JsonProcessingException;
10 import com.fasterxml.jackson.databind.JsonNode;
11 import com.fasterxml.jackson.databind.ObjectMapper;
12 
13 public class TreeModelDemo1 {
14  public static void main(String[] args) throws JsonProcessingException, IOException {
15      ObjectMapper objectMapper = new ObjectMapper();
16      File file = new File("jsondata.json");
17      JsonNode jsonNode = objectMapper.readTree(file);
18      Iterator iterator = jsonNode.fields();
19      while(iterator.hasNext()) {
20          Map.Entry entry = iterator.next();
21          System.out.println(entry.getKey() + ":" + entry.getValue() + ":" + entry.getValue().getNodeType().name());
22      }
23  }
24 }

Explanation

Once we obtain an instance of JsonNode, a top node which represents the top level object field in json. We can get all the other nodes as an iterator using the below method

jsonNode.fields()

This returns an iterator with key, value pair. Where key is the name of field in a json file and value is an instance of JsonNode.

jsondata.json

{
“firstName”: “Duke”,
“lastName”: “Java”,
“age”: 18,
“streetAddress”: “100 Internet Dr”,
“city”: “JavaTown”,
“state”: “JA”,
“postalCode”: “12345”,
“phoneNumbers”: [
{ “Mobile”: “111-111-1111” },
{ “Home”: “222-222-2222” }
]
}

Output

firstName:”Duke”:STRING
lastName:”Java”:STRING
age:18:NUMBER
streetAddress:”100 Internet Dr”:STRING
city:”JavaTown”:STRING
state:”JA”:STRING
postalCode:”12345″:STRING
phoneNumbers:[{“Mobile”:”111-111-1111″},{“Home”:”222-222-2222″}]:ARRAY

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s