Tuesday 29 June 2021

Moshi: Convert json to map

Step 1: Get an instance of ‘JsonAdapter’ to work with map data.

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

 

Step 2: Convert json to map.

Map<String, Object> map = jsonAdapter.fromJson(json);

 

Find the below working application.

 

JsonToMap.java
package com.sample.app;

import java.io.IOException;
import java.util.Map;

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

public class JsonToMap {
  public static void main(String args[]) throws IOException {
    String json = "{\n"
        + "  \"address\": {\n"
        + "    \"country\": \"India\",\n"
        + "    \"city\": \"Hyderabad\"\n"
        + "  },\n"
        + "  \"hobbies\": [\n"
        + "    \"Trekking\",\n"
        + "    \"Singing\"\n"
        + "  ],\n"
        + "  \"name\": \"Dhatri\",\n"
        + "  \"id\": 1\n"
        + "}\n"
        + "";
    
    Moshi moshi = new Moshi.Builder().build();
    JsonAdapter<Map<String, Object>> jsonAdapter = moshi.adapter(Types.newParameterizedType(Map.class, String.class, Object.class));

    Map<String, Object> map = jsonAdapter.fromJson(json);
    
    for(Map.Entry<String, Object> entry : map.entrySet()) {
      System.out.println(entry.getKey() + "->" + entry.getValue());
    }
  }

}

Output

address->{country=India, city=Hyderabad}
hobbies->[Trekking, Singing]
name->Dhatri
id->1.0


 


Previous                                                    Next                                                    Home

No comments:

Post a Comment