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

Tags: JSON moshi

Java Code Examples for com.squareup.moshi.JsonAdapter.fromJson()

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

Adding Moshi dependency into your project

Using Gradle

compile group: 'com.squareup.moshi', name: 'moshi', version: '1.8.0'

Using Maven

<dependency>
    <groupId>com.squareup.moshi</groupId>
    <artifactId>moshi</artifactId>
    <version>1.8.0</version>
</dependency>

How to use com.squareup.moshi.JsonAdapter.fromJson()

package simplesolution.dev;

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;

import java.io.IOException;
import java.util.List;

public class JsonAdapterFromJsonExamples {

    public static void main(String... args){
        String data = "[{\"name\":\"Sample JSON Serialization\",\"url\":\"https://simplesolution.dev\"},{\"name\":\"Java Tutorials\",\"url\":\"https://simplesolution.dev/java\"}]";
        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<List> jsonAdapter = moshi.adapter(List.class);
        try {
            List<Employee> objectFromJsonString = jsonAdapter.fromJson(data);
            System.out.println("Object from String: " + objectFromJsonString);
        }catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Happy Coding 😊