java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to convert object into JSON?

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 com.javacoderanch.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:

json = {"name":"Duke","address":"Menlo Park","dateOfBirth":"Feb 1, 2000 12:00:00 AM"}

Below is our Student class.

package com.javacoderanch.example.google.gson;

import java.util.Date;

public class Student {
    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;
    }
}