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 java.util.Arrays;

public class PojoToJSON {
    public static void main(String[] args) {
        Student student = new Student();
        student.setCourses(Arrays.asList("Engineering", "Finance", "Chemistry"));

        JSONObject object = new JSONObject(student);
        String json = object.toString();

Running this code produces the following result:


The Student class use in the code above:


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


Maven Central