728x90 AdSpace

Saturday, 12 October 2013

How to convert Object to JSON using Jackson

In this Tutorials we are going to see how to convert Java object to JSON String using Jackson data binding.
Jackson is high performance JSON processor library available in Java.
1. Create project called JSONExample.
2. Create package called com.javatutorialscorner.jackson  3. Create java class called JacksonPojo under com.javatutorialscorner.jackson
package com.javatutorialscorner.jackson;

import java.util.List;

public class JacksonPojo {
private int id;
private String name;
private List<String> list;

public int getId() {
return id;

public void setId(int id) {
this.id = id;

public String getName() {
return name;

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

public List<String> getList() {
return list;

public void setList(List<String> list) {
this.list = list;


4. add jackson-mapper-asl-1.9.13.jar, jackson-core-asl-1.9.13.jar into build path.

5. Now Create java class called JacksonWriteExample under com.javatutorialscorner.jackson


package com.javatutorialscorner.jackson;

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;

public class JacksonWriteExample {

* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
JacksonPojo pojo = null;
ObjectMapper mapper = null;
List<String> list = null;
try {
pojo = new JacksonPojo();
list = new ArrayList<String>();
list.add("Test - 198 ");
list.add("ODI - 463 ");
list.add("T20 - 1");
list.add("IPL - 78");
mapper = new ObjectMapper();
mapper.writeValue(new File("C:\\jtc\\javatutorialscorner.json"),
System.out.println("JSON String - "
+ mapper.writeValueAsString(pojo));
} catch (JsonGenerationException e) {
// TODO Auto-generated catch block
} catch (JsonMappingException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block



The writeValue() method used to write JSON String into file and writeValueAsString() method will return JSON String.

Now run the program see the following output in console and also JSON File created at specified location.

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

Annamalai is working as Technical Lead in Leading Telecom company with 5+ years experience in Identity and Access Management , Telecom and Networks, BigData, Java, Spring, Struts, Hibernate, AngularJS, and Enterprise Web Application Development.

Website: Java Tutorials Corner

Shop and help us

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


Post a Comment

Item Reviewed: How to convert Object to JSON using Jackson Rating: 5 Reviewed By: Annamalai Thangaraj