JSON to object, object to JSON in Java

JSON (JavaScript Object Notation) is the most popular data format used for web client/server communications.

Gson is the easiest way to convert a string in JSON format to Java Object and Java Object to a string in JSON format.

GSON. Maven Dependency

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

JSON to object with Gson

Let’s assume we have some String json. This contains JSON formatted MyClass object. We want to convert this json string to the object of MyClass.

    Gson gson = new Gson();
    MyClass myClass = gson.fromJson(json, MyClass.class);

That’s it.

Object to JSON

    Gson gson = new Gson();
    String json = gson.toJson(myClass);

If we need a human-readable json we can enable “pretty printing”

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    String json = gson.toJson(myClass);

You may also find these posts interesting: