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.gson;
import com.google.gson.Gson;
import org.kodejava.gson.support.Student;
import java.util.Calendar;
public class StudentToJson {
public static void main(String[] args) {
Calendar dob = Calendar.getInstance();
dob.set(2000, Calendar.FEBRUARY, 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:
json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}
Below is our Student
class.
package org.kodejava.gson.support;
import java.io.Serializable;
import java.util.Date;
public class Student implements Serializable {
private String name;
private String address;
private Date dateOfBirth;
public Student() {
}
public Student(String name, String address, Date dateOfBirth) {
this.name = name;
this.address = address;
this.dateOfBirth = dateOfBirth;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(Date dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
}
Maven Dependencies
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>
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