Sunday 5 January 2020

Gson: Convert HashMap to json string

Following snippet converts HashMap to json object.

Gson gson = new Gson();
Map<String,String> countriesAndCapitals = new HashMap<> ();
String json = gson.toJson(countriesAndCapitals);

App.java
package com.sample.app;

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

import com.google.gson.Gson;

public class App {

 public static void main(String args[]) {
  Gson gson = new Gson();

  Map<String, String> countriesAndCapitals = new HashMap<>();

  countriesAndCapitals.put("India", "Delhi");
  countriesAndCapitals.put("Nepal", "Katmandu");
  countriesAndCapitals.put("Canada", "Ottawa");

  String json = gson.toJson(countriesAndCapitals);

  System.out.println(json);
 }

}

Output
{"Canada":"Ottawa","Nepal":"Katmandu","India":"Delhi"}


Previous                                                    Next                                                    Home

No comments:

Post a Comment