Json to guava multimap

This example will demonstrate how to convert json to guava multimap using jackson JSON parser. In the set up, we will create a sample class NavItem and json that represent navigation elements. In addition, you will need to add jackson guava module to support JSON serialization and deserialization of Guava collection types.

Setup

Sample java class

class NavItem {

    private String linkText;
    private String url;

    ...
}

Sample json

{
   "123455":[
      {
         "key":"Java Exercises",
         "url":"www.leveluplunch.com/java/exercises/"
      },
      {
         "key":"Java Examples",
         "url":"www.leveluplunch.com/java/examples/"
      }
   ],
   "999999":[
      {
         "key":"Java Tutorials",
         "url":"www.leveluplunch.com/java/tutorials/"
      },
      {
         "key":"Java Examples",
         "url":"www.leveluplunch.com/java/examples/"
      }
   ]
}

Additional dependency

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-guava</artifactId>
  <version>2.2.0</version>
</dependency>

Google Guava

First we will create an ObjectMapper, a class that provides the ability to convert between java and json, to deserialize json to guava multimap. Next calling ObjectMapper.readValue passing json and calling constructMapLikeType that will create a MultiMap with string as a key and nav item as values. In addition, you will need to register GuavaModule which will extend guava functionality to the object mapper.

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

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new GuavaModule());

    Multimap<String, NavItem> navs = objectMapper.readValue(
            objectMapper.treeAsTokens(objectMapper.readTree(jsonString)),
            objectMapper.getTypeFactory().constructMapLikeType(
                    Multimap.class, String.class, NavItem.class));

    logger.info(navs);

    assertThat(navs.keys(), hasItems("123455", "999999"));
}

Output

{
123455=[
    NavItem{key=Java Exercises, url=www.leveluplunch.com/java/exercises/},
    NavItem{key=Java Examples, url=www.leveluplunch.com/java/examples/}
],
999999=[
    NavItem{key=Java Tutorials, url=www.leveluplunch.com/java/tutorials/},
    NavItem{key=Java Examples, url=www.leveluplunch.com/java/examples/}
]
}