Convert JSON to Hashmap using Jackson

This example will show the following:

  • how to convert json to a map using jackson
  • how to convert a java map to json using jackson

In the set up section we borrowed json snippet from json.org example that will be used in the each of the snippets below.

Setup

String sampleJson =
{  
  "ID":"SGML",
  "SortAs":"SGML",
  "GlossTerm":"Standard Generalized Markup Language",
  "Acronym":"SGML",
  "Abbrev":"ISO 8879:1986"
}

JSON to Map

First initializing jackson's object mapper is the heart of jackson as it provides functionality for converting between Java objects and matching JSON constructs. Next we will read the sameJson value from above and pass a TypeReference into an overloaded readValue method. TypeReference is a class used used for obtaining full generics type information and an additional constructor mapper.readValue(src, Map.class) but you get a nasty check style error. Finally we will assert that the map has the following keys using hamcrest.

@Test
public void json_to_map() throws JsonParseException, JsonMappingException,
        IOException {

    Map<String, Object> map = new HashMap<>();

    ObjectMapper mapper = new ObjectMapper();
    map = mapper.readValue(sampleJson,
            new TypeReference<HashMap<String, Object>>() {
            });

// OR map = mapper.readValue(sampleJson, HashMap.class);

    logger.info(sampleJson);

    assertThat(map.keySet(),
            hasItems("ID", "SortAs", "GlossTerm", "Acronym", "Abbrev"));
}

Java map to json

Flipping the snippet above around we will create a map object that resembles the same json value above. Instead of reading the value we will call writeValueAsString which will return the map as json in a java string.

@Test
public void java_map_to_json() throws JsonProcessingException {

    // initialize map
    Map<String, Object> map = new LinkedHashMap<>();
    map.put("ID", "SGML");
    map.put("SortAs", "SGML");
    map.put("GlossTerm", "Standard Generalized Markup Language");
    map.put("Acronym", "SGML");
    map.put("Abbrev", "ISO 8879:1986");

    ObjectMapper objectMapper = new ObjectMapper();
    String json = objectMapper.writeValueAsString(map);

    logger.info(json);

    assertEquals(json, sampleJson);
}