Sunday, 5 January 2020

Jackson: Convert HashMap to json string

Below snippet convert HashMap to json string.

ObjectMapper mapper = new ObjectMapper();
Map<String, String> countriesAndCapitals = new HashMap<>();
String json = mapper.writeValueAsString(countriesAndCapitals);

App.java
package com.sample.app;

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

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class App {

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


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

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

  String json = mapper.writeValueAsString(countriesAndCapitals);

  System.out.println(json);
 }

}

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



Previous                                                    Next                                                    Home

No comments:

Post a Comment