Jackson example – Read and write JSON


In this post,we will see how can we read and write JSON using Jackson.

Java JSON Tutorial Content:

    JSON Introduction JSON.simple example-read and write JSON GSON example-read and write JSON Jackson example – read and write JSON Jackson Streaming API - read and write JSON
After  reading and writing JSON using GSON,we will use another way(i.e. Jackson) of reading JSON.
Jackson is a high performance Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.

writeValue : It will convert simple pojo object to JSON.
         ObjectMapper mapper=new ObjectMapper();
         mapper.writeValue(new File("//Users//Arpit//country.json"), countryObj);
readValue : It will convert JSON to pojo object.
         ObjectMapper mapper=new ObjectMapper();
         BufferedReader br = new BufferedReader(
     new FileReader("//Users//Arpit//country.json"));

  //convert the json string back to object
  Country countryObj = mapper.readValue(br, Country.class);
Please note that there are many overloaded version of read and write value to support different parameters such as File,URL

<!-- adsense -->

In this post,we will read and write JSON using Jackson.
1). Create a java project named "jacksonJsonExample"

2) Add following maven dependency for jackson.
Pom.xml :
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>

 <groupId>com.arpit.java2blog</groupId>
 <artifactId>jacksonJsonExample</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>jar</packaging>

 <name>jacksonJsonExample</name>
 <url>http://maven.apache.org</url>

 <properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 </properties>
 <repositories>
  <repository>
   <id>codehaus</id>
   <url>http://repository.codehaus.org/org/codehaus</url>
  </repository>
 </repositories>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
  <dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.9.13</version>
  </dependency>
 </dependencies>
</project>
3) create a pojo named "Country.java"
package org.arpit.java2blog.pojo;

import java.util.ArrayList;
import java.util.List;

public class Country {

 String name;
 int population;
 private List<String> listOfStates;

 //getter and setter methods

 public String getName() {
      return name;

 public void setName(String name) {
  this.name = name;
 }

 public int getPopulation() {
  return population;
 }

 public void setPopulation(int population) {
  this.population = population;
 }

 public List<String> getListOfStates() {
  return listOfStates;
 }

 public void setListOfStates(List<String> listOfStates) {
 this.listOfStates = listOfStates;
 }

}

Write JSON to file:

4) Create a new class named "JacksonJsonWriteToFileExample.java" in src->org.arpit.java2blog.jacksonJsonExample
package com.arpit.java2blog.jacksonJsonExample;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * 
 * @author Arpit Mandliya
 *
 */
public class JacksonJsonWriteToFileExample 
{
    public static void main( String[] args )
    {
      Country countryObj=new Country();
       countryObj.setName("India");
       countryObj.setPopulation(1000000);
       List<String> listOfStates=new ArrayList<String>();
       listOfStates.add("Madhya Pradesh");
       listOfStates.add("Maharashtra");
       listOfStates.add("Rajasthan");
       
       countryObj.setListOfStates(listOfStates);
       ObjectMapper mapper=new ObjectMapper();
       try {
   mapper.writeValue(new File("//Users//Arpit//country.json"), countryObj);
   
  } catch (JsonGenerationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (JsonMappingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
}


Run above program and content of file country.json will be as below :
{"name":"India","population":1000000,"listOfStates":["Madhya Pradesh","Maharashtra","Rajasthan"]}

Write formatted JSON to file:

5) If you want to prettify json, you an use mapper.writerWithDefaultPrettyPrinter() to do it. Create a new class named "JacksonJsonWriteToFileFormattedExample.java" in src->org.arpit.java2blog.jacksonJsonExample
package com.arpit.java2blog.jacksonJsonExample;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * 
 * @author Arpit Mandliya
 *
 */
public class JacksonJsonWriteToFileFormattedExample 
{
    public static void main( String[] args )
    {
      Country countryObj=new Country();
       countryObj.setName("India");
       countryObj.setPopulation(1000000);
       List<String> listOfStates=new ArrayList<String>();
       listOfStates.add("Madhya Pradesh");
       listOfStates.add("Maharashtra");
       listOfStates.add("Rajasthan");
       
       countryObj.setListOfStates(listOfStates);
       ObjectMapper mapper=new ObjectMapper();
       try {
   mapper.writerWithDefaultPrettyPrinter().writeValue(new File("//Users//Arpit//country.json"), countryObj);
   System.out.println("Json written to the file");
  } catch (JsonGenerationException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (JsonMappingException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
    }
}


Run above program and content of file country.json will be as below :
{
  "name" : "India",
  "population" : 1000000,
  "listOfStates" : [ "Madhya Pradesh", "Maharastra", "Rajasthan" ]
}

Read JSON to file:

Here we will read above created JSON file.
6) Create a new class named "JacksonJsonReadFromFileExample.java" in src->org.arpit.java2blog.jacksonJsonExample
package com.arpit.java2blog.jacksonJsonExample;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;

import org.codehaus.jackson.map.ObjectMapper;

public class JacksonJsonReadFromFileExample {

 public static void main(String[] args)
 {
  ObjectMapper mapper =new ObjectMapper();
  try{
   System.out.println("Reading JSON from a file");
   System.out.println("----------------------------");

   BufferedReader br = new BufferedReader(
     new FileReader("//Users//Arpit//country.json"));

   //convert the json string back to object
   Country countryObj = mapper.readValue(br, Country.class);

   System.out.println("Name Of Country: "+countryObj.getName());


   System.out.println("Population: "+countryObj.getPopulation());

   System.out.println("States are :");

   List<String> listOfStates = countryObj.getListOfStates();
   for (int i = 0; i < listOfStates.size(); i++) {
    System.out.println(listOfStates.get(i));
   }

  } catch (IOException e) {
   e.printStackTrace();
  }

 }
}

Run above program and you will get following output:
Reading JSON from a file
----------------------------
Name Of Country: India
Population: 1000000
States are :
Madhya Pradesh
Maharashtra
Rajasthan 

click to begin
20KB .zip

Project Structure: 


Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012