Here I am going to show you how to convert a Java object to JSON format using Jackson.

Java object to JSON :

We can convert the Java object to JSON format text using Jackson library. To use the Jackson, we need to add the below Jackson jar file to your classpath.

jackson-all-1.9.0.jar

Or you can add the below dependency on your project pom.xml file.

[xml]

<dependencies>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.0</version>
</dependency>
</dependencies>

[/xml]

Java object to JSON Example:

Here I am going to create a Student object and converting to JSON string.

Student.java

class Student {
    private int studentId;
    private String studentName;
    private String roleNumber;
    private String standard;
    public int getStudentId() {
        return studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public String getRoleNumber() {
        return roleNumber;
    }
    public String getStandard() {
        return standard;
    }
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public void setRoleNumber(String roleNumber) {
        this.roleNumber = roleNumber;
    }
    public void setStandard(String standard) {
        this.standard = standard;
    }
    @Override public String toString() {
        return "Student [studentId=" + studentId + ", studentName=" + studentName + ", roleNumber=" + roleNumber + ", standard=" + standard + "]";
    }
}

Converting the Student Java object to JSON string.

[java]

package com.onlinetutorialspoint.json;

import java.io.IOException;

import org.codehaus.jackson.map.ObjectMapper;

public class Java_Object_TO_Json {
    public static void main(String[] a){
        
        Student student = new Student();
        student.setStudentId(1001);
        student.setStudentName("Rahul");
        student.setRoleNumber("54");
        student.setStandard("5th");
        ObjectMapper mapperObj = new ObjectMapper();
        try {
            String jsonFormat = mapperObj.writeValueAsString(student);
            System.out.println(jsonFormat);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

[/java]

Output:

{"studentId":1001,"studentName":"Rahul","roleNumber":"54","standard":"5th"}

Happy Learning  🙂

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment