Deserializes JSON string into Java object using Gson.fromJson() with Gson

Tags: JSON gson

Java Code Examples for com.google.gson.Gson.fromJson()

This method to deserializes a JSON string into a Java object of the specified class.

Adding Gson dependency into your project

Using Gradle

compile group: 'com.google.code.gson', name: 'gson', version: '2.8.5'

Using Maven

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

How to use com.google.gson.Gson.fromJson()

package simplesolution.dev;

import com.google.gson.Gson;

import java.util.List;
import java.util.Map;

public class GsonFromJsonExamples {

    public static void main(String... args) {
        String data = "[{\"name\":\"Sample JSON Serialization\",\"url\":\"https://simplesolution.dev\"},{\"name\":\"Java Tutorials\",\"url\":\"https://simplesolution.dev/java\"}]";
        Gson gson = new Gson();
        List<Map<String, String>> objectFromJsonString = gson.fromJson(data, List.class);
        System.out.println("Object from String: " + objectFromJsonString);
    }
}

Happy Coding 😊