We are moved to new domain
Click -> www.ehowtonow.com
Saturday, 12 October 2013

JSON Tree Model in Jackson


In this Tutorials we are going to see how to read and write JSON Tree model using Jackson JsonNode.
The JsonNode is used to read and write tree structured date.It is similar to XML Dom tree.
1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.jackson 
3. add jackson-mapper-asl-1.9.13.jar, jackson-core-asl-1.9.13.jar into build path.
4. Create java class called JacksonTreeExample under com.javatutorialscorner.jackson
JacksonTreeExample.java
package com.javatutorialscorner.jackson;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;

import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ObjectNode;

public class JacksonTreeExample {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ObjectMapper mapper = null;

mapper = new ObjectMapper();

try {
JsonNode root = mapper.readTree(new File(
"C:\\jtc\\javatutorialscorner.json"));

JsonNode id = root.path("id");
System.out.println("ID : " + id.getIntValue());
JsonNode name = root.path("name");
System.out.println("Name : " + name.getTextValue());
JsonNode list = root.path("list");
Iterator<JsonNode> iterator = list.getElements();
while (iterator.hasNext()) {
JsonNode format = iterator.next();
System.out.println("Format : " + format.getTextValue());
}

((ObjectNode) root).put("id", 7);
((ObjectNode) root).put("name", "Dhoni");
mapper.writeValue(new File("C:\\jtc\\javatutorialscorner.json"),
root);
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}

The javatutorialscorner.json file contains following String

{"id":10,"name":"Tendulkar","list":["Test - 198 ","ODI - 463 ","T20 - 1","IPL - 78"]}

Now run the program see the following output in console.

ID : 10

Name : Tendulkar

Format : Test - 198

Format : ODI - 463

Format : T20 - 1

Format : IPL - 78

and also javatutorialscorner.json File content replace with following contents.

{"id":7,"name":"Dhoni","list":["Test - 198 ","ODI - 463 ","T20 - 1","IPL - 78"]}

Shop and help us

Flipkart Offer Snapdeal offer Amazon.in offer Amazon.com offer
  • Blogger Comments
  • Facebook Comments
  • Disqus Comments

0 comments:

Post a Comment

Item Reviewed: JSON Tree Model in Jackson Rating: 5 Reviewed By: eHowToNow