Tuesday, 29 June 2021

Moshi: Convert map to json

Step 1: Get an instance of JsonAdapter.

Moshi moshi = new Moshi.Builder().build();
JsonAdapter<Map<String, Object>> jsonAdapter = moshi.adapter(Types.newParameterizedType(Map.class, String.class, Object.class));

 

Step 2: Convert the map to json.

String json = jsonAdapter.indent("  ").toJson(employeeMap);

 

Find the below working application.

MapToJson.java

package com.sample.app;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

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

public class MapToJson {
  public static void main(String args[]) {
    Map<String, Object> employeeMap = new HashMap<>();

    employeeMap.put("id", 1);
    employeeMap.put("name", "Dhatri");
    employeeMap.put("hobbies", Arrays.asList("Trekking", "Singing"));

    Map<String, Object> addressMap = new HashMap<>();
    addressMap.put("city", "Hyderabad");
    addressMap.put("country", "India");

    employeeMap.put("address", addressMap);

    Moshi moshi = new Moshi.Builder().build();
    JsonAdapter<Map<String, Object>> jsonAdapter = moshi.adapter(Types.newParameterizedType(Map.class, String.class, Object.class));

    String json = jsonAdapter.indent("  ").toJson(employeeMap);
    System.out.println(json);
  }

}

 

Output

{
  "address": {
    "country": "India",
    "city": "Hyderabad"
  },
  "hobbies": [
    "Trekking",
    "Singing"
  ],
  "name": "Dhatri",
  "id": 1
}

 

 

 

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment