How do I convert Java Object to JSON?

To convert Java objects or POJOs (Plain Old Java Objects) to JSON we can use one of JSONObject constructor that takes an object as its argument. In the following example we will convert Student POJO into JSON string. Student class must provide the getter methods, JSONObject creates JSON string by calling these methods.

In this code snippet we do as follows:

  • Creates Student object and set its properties using the setter methods.
  • Create JSONObject called object and use the Student object as argument to its constructor.
  • JSONObject use getter methods to produces JSON string.
  • Call object.toString() method to get the JSON string.
package org.kodejava.json;

import org.json.JSONObject;
import org.kodejava.json.support.Student;

import java.util.Arrays;

public class PojoToJSON {
    public static void main(String[] args) {
        Student student = new Student();
        student.setId(1L);
        student.setName("Alice");
        student.setAge(20);
        student.setCourses(Arrays.asList("Engineering", "Finance", "Chemistry"));

        JSONObject object = new JSONObject(student);
        String json = object.toString();
        System.out.println(json);
    }
}

Running this code produces the following result:

{"courses":["Engineering","Finance","Chemistry"],"name":"Alice","id":1,"age":20}

The Student class use in the code above:

package org.kodejava.json.support;

import java.util.List;

public class Student {
    private Long id;
    private String name;
    private int age;
    private List<String> courses;

    // Getters and Setters removed for simplicity
}

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20240303</version>
    </dependency>
</dependencies>

Maven Central

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.