coding made simple with some delicious cake

How to parse JSON using Jackson

In this post we will provide an example on how to parse JSON using jackson java library. Jackson is one of the most popular and powerful JSON java processors, for more information please check out the reference section for more in-depth documentation.

Setup:

In order to use the jackson library you will need to include the following dependancy to your project.

1

2

3

4

5

<dependency>

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

<artifactId>jackson-core</artifactId>

<version>2.9.5</version>

</dependency>

How to parse JSON using jackson:

The example below shows how to parse a JSON string.

Parse Json string using Jackson

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

@Test

publicvoidparseJsonString()throwsIOException{

Stringjson="{\n"+

" \"name\": \"blobby\",\n"+

" \"age\": 22,\n"+

" \"address\": {\n"+

" \"line1\": \"Earth\",\n"+

" \"postcode\": \"E1 E23\"\n"+

" }\n"+

"}";

ObjectMapper objectMapper=newObjectMapper();

JsonNode jsonNode=objectMapper.reader().readTree(json);

System.out.println("name = "+jsonNode.get("name").asText());

System.out.println("age = "+jsonNode.get("age").asInt());

ObjectNode address=(ObjectNode)jsonNode.get("address");

System.out.println("line1 = "+address.get("line1").asText());

System.out.println("postcode = "+address.get("postcode").asText());

}

A few points from the example above:

ObjectMapper is the main entry point when you would like to read / write JSON (from a string, file POJO etc..)

JsonNode represents all or part of the json object, you can use this to access or navigate your json object.

Output:

Running the above code produces the following output

1

2

3

4

name = blobby

age = 22

line1 = Earth

postcode = E1 E23

In conclusion, I hope you found this post useful and it gives you an insight on how to use the jackson library