Convert java object to Json using jackson library

In this example we are going to learn how to convert java object into the json format.

Lets create a maven project into the eclipse workspace. Open up the pom.xml file and paste the following code inside the project node.

If you are not using maven then you may download the library from the google and add it to the class path.




Lets create the User object first. This is a java object with 2 fields and a list.


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

public class User {

    private int id = 01;
    private String name = "Amzi";
    private List<String> messages = new ArrayList<String>();

        messages.add("Your name is - " + name);
        messages.add("Your Id is - " + id);
        messages.add("Welcome to the world!!!");


    public int getId() {
        return id;

    public void setId(int id) { = id;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public List<String> getMessages() {
        return messages;

    public void setMessages(List<String> messages) {
        this.messages = messages;

    public String toString() {
        return "User [id=" + id + ", name=" + name + ", " + "messages="
                + messages + "]";

Jackson library provides us the writeValue() method and which is available in ObjectMapper class. In this method we are going to pass the location where we want to save the json file.


import org.codehaus.jackson.JsonGenerationException;

public class Java2Json {
    public static void main(String[] args) {

        User user = new User();
        ObjectMapper mapper = new ObjectMapper();

        try {
            // converts user object to json string, and save to a file
                    new File("c:\\Users\\Amzi\\Desktop\\user.json"), user);

            // display to console
        } catch (JsonGenerationException e) {
        } catch (JsonMappingException e) {
        } catch (IOException e) {

Now, we are done parsing the java object into the json format. Once we run the above java class, we are going to get following output into the console and also the same output will be saved inside the user.json file.


  "messages" : [ "Your name is - Amzi", "Your Id is - 1", "Welcome to the world!!!" ],
  "name" : "Amzi",
  "id" : 1

1 comment:

  1. I have read your blog its very attractive and impressive. I like it your blog.

    Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

    Java Online Training Java Online Training JavaEE Training in Chennai Java EE Training in Chennai