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.