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
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
JacksonPojo.java
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

JacksonWriteExample.java

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();
pojo.setId(10);
pojo.setName("Tendulkar");
list = new ArrayList<String>();
list.add("Test - 198 ");
list.add("ODI - 463 ");
list.add("T20 - 1");
list.add("IPL - 78");
pojo.setList(list);
mapper = new ObjectMapper();
mapper.writeValue(new File("C:\\jtc\\javatutorialscorner.json"),
pojo);
System.out.println("JSON String - "
+ mapper.writeValueAsString(pojo));
} 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();
}

}

}

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"]}

0 comments

Post a Comment