Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

This quick tutorial will show how to serialize a Java entity with Jackson 2 using a Custom Serializer.

If you want to dig deeper and learn other cool things you can do with the Jackson 2 – head on over to the main Jackson tutorial.

2. Standard Serialization of an Object Graph

Let’s define 2 simple entities and see how Jackson serializes these without any custom logic:

public class User {
    public int id;
    public String name;
}
public class Item {
    public int id;
    public String itemName;
    public User owner;
}

Now, let’s serialize an Item entity with a User entity:

Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = new ObjectMapper().writeValueAsString(myItem);

This will result in a full JSON representation for both entities:

{
    "id": 1,
    "itemName": "theItem",
    "owner": {
        "id": 2,
        "name": "theUser"
    }
}

3. Custom Serializer on the ObjectMapper

Now, let’s simplify the JSON output above by only serializing the id of the User, not the entire User object; we’d like to get the following, simpler JSON:

{
    "id": 25,
    "itemName": "FEDUfRgS",
    "owner": 15
}

Simply put, we’ll have to define a custom Serializer for Item objects:

public class ItemSerializer extends StdSerializer<Item> {
    
    public ItemSerializer() {
        this(null);
    }
  
    public ItemSerializer(Class<Item> t) {
        super(t);
    }

    @Override
    public void serialize(
      Item value, JsonGenerator jgen, SerializerProvider provider) 
      throws IOException, JsonProcessingException {
 
        jgen.writeStartObject();
        jgen.writeNumberField("id", value.id);
        jgen.writeStringField("itemName", value.itemName);
        jgen.writeNumberField("owner", value.owner.id);
        jgen.writeEndObject();
    }
}

Now, we need to register this custom serializer with the ObjectMapper for the Item class, and perform the serialization:

Item myItem = new Item(1, "theItem", new User(2, "theUser"));
ObjectMapper mapper = new ObjectMapper();

SimpleModule module = new SimpleModule();
module.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(module);

String serialized = mapper.writeValueAsString(myItem);

That’s it – we now have a simpler, custom JSON serialization of the Item->User entities.

4. Custom Serializer on the Class

We can also register the serializer directly on the class, instead of on the ObjectMapper:

@JsonSerialize(using = ItemSerializer.class)
public class Item {
    ...
}

Now, when performing standard serialization:

Item myItem = new Item(1, "theItem", new User(2, "theUser"));
String serialized = new ObjectMapper().writeValueAsString(myItem);

We will get the custom JSON output, created by the serializer, specified via @JsonSerialize:

{
    "id": 25,
    "itemName": "FEDUfRgS",
    "owner": 15
}

This is helpful when the ObjectMapper cannot be accessed and configured directly.

5. Conclusion

This article illustrated how to get to a custom JSON output with Jackson 2, by using Serializers.

The implementation of all these examples and code snippets can be found on GitHub – this is a Maven-based project, so it should be easy to import and run as it is.

Course – LS (cat=JSON/Jackson)

Get started with Spring and Spring Boot, through the Learn Spring course:

>> CHECK OUT THE COURSE
res – Jackson (eBook) (cat=Jackson)
Comments are closed on this article!