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
Studentobject and set its properties using the setter methods. - Create
JSONObjectcalledobjectand use theStudentobject as argument to its constructor. JSONObjectuse 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>
