W3docs

Converting JSON data to Java object

To convert JSON data to a Java object, you can use the fromJson method of the Gson class.

To convert JSON data to a Java object, you can use the fromJson method of the Gson class.

Here's an example of how to do it:


import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

// Sample JSON data
String jsonData = "{\"name\":\"John\",\"age\":30}";

// Create a Gson instance
Gson gson = new Gson();

// Define the type of the object you want to convert to
Type type = new TypeToken<MyObject>(){}.getType();

// Convert the JSON data to an object of the specified type
MyObject obj = gson.fromJson(jsonData, type);

// Target class definition
class MyObject {
    private String name;
    private int age;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

In this example, jsonData is a string containing the JSON data, and MyObject is the class of the object you want to create. The TypeToken class is used to specify the type of the object in a type-safe way.