Serializes Java object into JSON String using JsonAdapter.toJson() with Moshi

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

This method to serializes the Java object into JSON string.


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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonAdapterToJsonExamples {

    public static void main(String... args) {
        List<Map<String, String>> data = new ArrayList<>();
        Map<String, String> item1 = new HashMap<>();
        item1.put("name", "Sample JSON Serialization");
        item1.put("url", "");

        Map<String, String> item2 = new HashMap<>();
        item2.put("name", "Java Tutorials");
        item2.put("url", "");

        Moshi moshi = new Moshi.Builder().build();
        JsonAdapter<List> jsonAdapter = moshi.adapter(List.class);
        String jsonStringFromObject = jsonAdapter.toJson(data);
        System.out.println("JSON String from Object: " + jsonStringFromObject);

Happy Coding 😊