Convert JSON to Map or Map to Json in Java

One of the common uses cases while working with json is to convert it to a java object or convert java object to json. There is an open source library available in java which helps in processing json objects.

Add the Jackson dependency in pom.xml file



The Java class :

public static void main(String args[]) {
        ObjectMapper mapper = new ObjectMapper();
        Map m = new HashMap();
        Map personMap = new HashMap<>();
        Map personDetail = new HashMap();
        personDetail.put("firstname", "Bob");
        personDetail.put("lastname", "jackson");
        personDetail.put("age", "12");
        personDetail.put("city", "Berlin");

        personMap.put("person", personDetail);
        //convert Map to json string
        try {
        } catch (IOException e) {

        // convert json to Map
        String json = "{\"person\":{\"age\":\"12\",\"lastname\":\"jackson\""
                + ",\"firstname\":\"Bob\",\"city\":\"Berlin\"}}"
        try {
            Map map = mapper.readValue(json, Map.class);
            System.out.println("Map is " + map);
        } catch (Exception e) {

Output is

Output: {“person”:{“age”:”12″,”lastname”:”jackson”,”firstname”:”Bob”,”city”:”Berlin”}}

Map is {person={age=12, lastname=jackson, firstname=Bob, city=Berlin}}

ObjectMapper mapper = new ObjectMapper();

Creating an object of ObjectMapper is a expensive operation and as best practice it should be created as a singleton object in a class.

Format Json String using JsonSerializer.

At times it is required to format the values while creating the json for eg Date, numeric value. The jackson json library provide a class JsonSerializer which helps in formatting the Object value.

For e.g
Convert the date return from DB in MM-dd-yyyy

class Person{

private String name;
private String city;
private Date DOB;

	public String getName() {
		return name;
	public void setName(String name) { = name;
	public String getCity() {
		return city;
	public void setCity(String city) { = city;
	public Date getDOB() {
		return DOB;
        @JsonSerialize(using = JsonDateSerializer.class)
	public void setDOB(Date dOB) {
		DOB = dOB;

public class JsonDateSerializer extends JsonSerializer {
	public void serialize(Object value, JsonGenerator gen, SerializerProvider arg2) throws IOException, JsonProcessingException {

	SimpleDateFormat formatter =
           new SimpleDateFormat("MM-dd-yyyy");
	String formattedDate = formatter.format(value);