coding made simple with some delicious cake

Convert a JSON array to a List using Jackson

In this post we will provide an example of how to convert a JSON array to a List using Jackson.

Setup:

In this example you will need to add the following dependancy

1

2

3

4

5

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-core</artifactId>

<version>2.9.5</version>

</dependency>

Convert a JSON array to a list:

The example below shows how to convert a JSON array to a java list using Jackson.

Java

1

2

3

4

5

6

7

8

9

10

11

12

@Test

publicvoidconvertJsonArrayToList(){

Stringjson="[\"Element1\",\"Element2\", \"Element3\"]";

ObjectMapper objectMapper=newObjectMapper();

try{

List elements=objectMapper.readValue(json,List.class);

System.out.println("elements = "+elements);

}catch(IOExceptione){

e.printStackTrace();

fail();

}

}

As you can see from the above example, the ObjectMapper class has a useful method readValue which takes a JSON string and converts it to the object class you specify as the 2nd argument (in this case a List)