logo

Deserializes JSON string into Java object using JsonAdapter.fromJson() with 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.

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 😊

Tags: