Convert JSON String to/from Java Object in Java (Gson Library)

Maven dependency of Google Gson Library

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Convert JSON to/from Java Object in Java (Gson):

import com.google.gson.Gson;

class Person {
    private String name;
    private int age;

    public String getName() {return name;}
    public int getAge() {return age;}
}

public class JsonParser {

    // Constructors, getters, setters...

    public static void main(String[] args) {
        String jsonString = "{\"name\":\"Mika\",\"age\":30}";

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

        // Convert JSON to Java Object
        Person person = gson.fromJson(jsonString, Person.class);

        // Access the Java Object
        System.out.println("JSON to Person:");
        System.out.println("Name: " + person.getName());
        System.out.println("Age: " + person.getAge());

        String json = gson.toJson(person);
        System.out.println("Person to JSON String:");
        System.out.println(json);
    }
}

Output:

JSON to Person:
Name: Mika
Age: 30
Person to JSON String:
{"name":"Mika","age":30}
Scroll to Top