coding made simple with some delicious cake

Jackson custom serializer

In this post we will provide an example of how to configure a Jackson custom serializer when using the Jackson library.

Setup

You will need to add the following dependency

pom.xml

1

2

3

4

5

<dependency>

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

<artifactId>jackson-core</artifactId>

<version>2.9.5</version>

</dependency>

Add the following classes if you wish to follow the example below

User class

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

publicclassUser{

privateStringname;

privateintage;

privateAddress address;

publicUser(Stringname,intage,Address address){

this.name=name;

this.age=age;

this.address=address;

}

publicStringgetName(){

returnname;

}

publicIntegergetAge(){

returnage;

}

publicAddress getAddress(){

returnaddress;

}

}

Address class

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

publicclassAddress{

privateStringline1;

privateStringpostcode;

publicAddress(Stringline1,Stringpostcode){

this.line1=line1;

this.postcode=postcode;

}

publicStringgetLine1(){

returnline1;

}

publicStringgetPostcode(){

returnpostcode;

}

}

Jackson custom serializer

The first example shows the default behaviour. It uses the ObjectMapper to convert a User object to JSON.

Java

1

2

3

4

5

User user=newUser("Peter",44,newAddress("vegan street","E1"));

ObjectMapper objectMapper=newObjectMapper();

Stringjson=objectMapper.writeValueAsString(user);

System.out.println(json);

Running the above code produces the following JSON

1

2

3

4

5

6

7

8

{

"name":"Peter",

"age":44,

"address":{

"line1":"vegan street",

"postcode":"E1"

}

}

Now lets say we do not want to have an address object in the JSON and instead we want to have line1 and postcode as top level fields. In this scenario we will need to provide a custom serializer as shown below.

Below is our custom UserSerializer, it ensures that line1 and postcode are top level fields and the address object is removed.