In this example we are using Google Gson to convert an object (Student object) into JSON notation. Practically we can use this library to convert any object in Java and it is quite simple. You just need to create an instance of Gson class and then call the .toJson() method and pass the object to be converted into JSON string.
package org.kodejava.example.google.gson;
import com.google.gson.Gson;
import java.util.Calendar;
public class StudentToJson {
public static void main(String[] args) {
Calendar dob = Calendar.getInstance();
dob.set(2000, 1, 1, 0, 0, 0);
Student student = new Student("Duke", "Menlo Park", dob.getTime());
Gson gson = new Gson();
String json = gson.toJson(student);
System.out.println("json = " + json);
}
}
When you run the example above you'll get an output like: