How do I convert JSON into object?

Category: com.google.gson, viewed: 4K time(s).

On the previous example, How do I convert object to JSON? we convert object into JSON string. In this example you'll see how to do the opposite, converting the JSON string back into the object.

To convert JSON string to object use Gson.fromJson() method. This method takes the JSON string and the object type of the string to be converted.

package org.kodejava.example.google.gson;

import com.google.gson.Gson;

public class JsonToStudent {
    public static void main(String[] args) {
        String json = "{\"name\":\"Duke\",\"address\":\"Menlo Park\",\"dateOfBirth\":\"Feb 1, 2000 12:00:00 AM\"}";

        Gson gson = new Gson();
        Student student = gson.fromJson(json, Student.class);

        System.out.println("student.getName()        = " + student.getName());
        System.out.println("student.getAddress()     = " + student.getAddress());
        System.out.println("student.getDateOfBirth() = " + student.getDateOfBirth());
    }
}

This example will print the following result:

student.getName()        = Duke
student.getAddress()     = Menlo Park
student.getDateOfBirth() = Tue Feb 01 00:00:00 CST 2000

You can find the Student class on the previous example mentioned at the beginning of this example.

Powered by Disqus