Following
snippet converts HashMap to json object.
Gson gson
= new Gson();
Map<String,String>
countriesAndCapitals = new HashMap<> ();
String
json = gson.toJson(countriesAndCapitals);
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"}
No comments:
Post a Comment