Sunday 5 January 2020

Genson: Convert HashMap to json string

Below snippet convert a map to json string.

Genson genson = new Genson();
Map<String, String> countriesAndCapitals = new HashMap<>();
String json = genson.serialize(countriesAndCapitals);

App.java
package com.sample.app;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.owlike.genson.Genson;

public class App {

 public static void main(String args[]) throws JsonProcessingException {
  Genson genson = new Genson();

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

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

  String json = genson.serialize(countriesAndCapitals);

  System.out.println(json);
 }

}

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


Previous                                                    Next                                                    Home

No comments:

Post a Comment