Json array to ArrayList jackson

This example will demonstrate how to convert a json array to a java ArrayList using jackson JSON parser. In the set up, we will create a sample class NavItem and a json array to represent navigation elements.

Setup

Sample java class

class NavItem {

    private String linkText;
    private String url;

    ...
}

Sample json array

[
   {
      "key":"Level up lunch",
      "url":"www.leveluplunch.com"
   },
   {
      "key":"Java examples",
      "url":"www.leveluplunch.com/java/examples/"
   },
   {
      "key":"Java exercises",
      "url":"www.leveluplunch.com/java/exercises/"
   },
   {
      "key":"Java tutorials",
      "url":"www.leveluplunch.com/java/tutorials/"
   }
]

Jackson

First we will create an ObjectMapper, a class that provides the ability to convert between java and json, to deserialize json to java ArrayList. Next calling ObjectMapper.readValue passing json and call a method that creates a collection of a specified NavItem type.

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

    ObjectMapper objectMapper = new ObjectMapper();

    List<NavItem> navigation = objectMapper.readValue(
            jsonString,
            objectMapper.getTypeFactory().constructCollectionType(
                    List.class, NavItem.class));

    logger.info(navigation);

    assertEquals(4, navigation.size());

}

Output

[
NavItem{key=Level up lunch, url=www.leveluplunch.com},
NavItem{key=Java examples, url=www.leveluplunch.com/java/examples/},
NavItem{key=Java exercises, url=www.leveluplunch.com/java/exercises/},
NavItem{key=Java tutorials, url=www.leveluplunch.com/java/tutorials/}
]