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
calledobject
and use theStudent
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>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024