I just released Module 10 in the Master Class of “REST with Spring”:

>> THE "REST WITH SPRING" CLASSES

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.

Go deeper into building a REST API with Spring:

>> CHECK OUT THE COURSE

  • RickJWagner

    Great tutorial. Simple and right to the point. Thank you.

  • Avi

    Thanks!
    I have one question:
    I have a class that sometime i want to use a custom serializer and sometimes i want to use the regular default serializer. is it possible?

    an example:
    Lets say i have a person class with a first name and a family name and i want to make a custom serializer to serialize just the first name but in some other cases i want to use the default serializer to serialize all of the person properties.

    Thanks.

    • Hey Avi,
      I think your best best is to work with 2 ObjectMappers – one with and the other without the serializer. As far as I’m aware, the API doesn’t support providing your own serializer on each call. That being said, the API is always evolving, so if you really need it, it may be worth asking and maybe opening up an issue to make it happen.
      Cheers,
      Eugen.

      • Avi

        Hey Eugen,

        Thanks for the reply! (and sorry for the late response).

        1) I didn’t completely understand how to register the custom serializer with the ObjectMapper. where do I need to write this code?

        2) After I work with 2 object mappers, how do I determine when it will be serialized with the custom serialized or with the default one?

        Thanks again.

        • Hey Avi,
          1. To register the custom serializer with the mapper, check out the snippet of code above:

          mapper.registerModule(module);

          2. That depends on who is that actually triggers the serialization; if you have controll over that (from your question, I assumed that you do) – then you will simply pick the right mapper for your need – you will basically pick which one.
          If this is a web app – for example, a Spring app – then that’s harder to do.
          Cheers,
          Eugen.

  • Stephane

    Hi Eugen, thanks for the Jackson series, I wonder how to put it to use in my demo Spring REST application for which I already use a ResourceAssemblerSupport class. You’d have an example where the two can play together ? Thanks.

    • I haven’t yet written about spring-hateoas – but I do have it on my todo list – I’m bumping it up on the list if so that I get to it soon. Cheers,
      Eugen.

      • Stephane

        No pressure… Thanks Eugen !

      • Stephane

        Or maybe it’s a contradiction in goals…

  • Stephane

    Hi Eugen,

    It would be cool if your example here showed one object property as itself being a serialized object.

    Cheers,

    • Stephane

      I think I found it. Simple.

      jgen.writeObjectField(“address”, adminResource.getAddressResource());

      • Yeah, that’s the way to write out an entire object – thanks for the note. Cheers,
        Eugen.

  • Hi,
    I am using Jackson library for my JSON serialization and de-serialization process. I would like to know how can I enforce a custom serialization property for a single property? I want to keep the remaining property by default. Whereas I need to change the transformation for one property. Is it possible without add the logic for all other properties?

    • I think I understand what you’re asking, but I’m not 100% sure – an example would be great. As a quick sidenote – if you need very granular control over the serialization and deserialziation processes – you’ll probably want to look at a custom Serializer/Deserializer. Cheers – and waiting for an example,
      Eugen.

  • Maksim Murujev

    Will this work with Spring AMQP ??

    • Well, AMQP is just the underlying protocol so it should work perfectly fine. That being said – I haven’t tried that combination before.

  • sprewell

    Hi! First of all, I´d like to thank you for your great tutorial.

    About this post, exists any way to create an annotation to use in fields, in order to use in a custom serilization? I mean, for example in the next POJO

    public class User {

    public int id;

    public String name;

    @IgnoreOnLog// custom annotation to avoid print this field in log

    public String pass;

    }

    Can I define a custom Serializer that i can use to write as string on loggers without print fields annotated with @IgnoreOnLog on any class? How it will be?

    Using GSON i have done it with a custom ExclusionStrategy, but i would like to do it using Jakson

    Thanks in advance!

  • Kunal Patel

    Hi, thanks for the concise and to-the-point tutorial.

    I wanted to check that – how I can ignore null/empty values while serialization. I have rest API in spring and want to ignore null/empty values for given POJO while serialization in JSON response. And I am using jackson for all json utilities.

    Thanks in advance.
    /kp

  • Kent Johnson

    Thank you very much! This worked perfectly for me.

  • Manish Dubey

    Thank you very much!!! Great tutorial for custom serialization.

  • Przemek

    Hi,
    Is another, simpler way to define User serialization in Item class ? I don’t want to define custom serializer and modify User class definition. Is it necessery to define own serializer when only one field (which is the type of another class- like User in example) must be serialized differently from default ?

    • Grzegorz Piwowarek

      I think that MixIn is what you might be looking for
      http://wiki.fasterxml.com/JacksonMixInAnnotations

    • Przemek

      @grzegorz_piwowarek:disqus ty for reply.

      Ok, i have solution for such cases:

      public abstract class ItemMixIn extends Item{
      @Override

      @JsonSerialize(using = UserAsIdSerializer.class)
      public abstract User getOwner(); //should be defined in Item.class
      }

      class UserAsIdSerializer extends JsonSerializer{
      @Override
      public void serialize(User user, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {
      gen.writeString(user.getId());
      }
      }

  • Rafał

    What do :
    public ItemSerializer() {
    this(null);
    }

    ?

    • Grzegorz Piwowarek

      Default StdSerializer has null as a handledType(which is equal to Object.class) so here we are just following this convention

      • Rafał

        Thank you Grzegorz 🙂

  • Grant Walker

    What is the difference between the 2 constructors?
    Is there a way to create a new constructor that accepts my own parameters?

    • Grzegorz Piwowarek

      The default constructor encapsulates the internal logic that handles “null” as an Object.class which makes it more user-friendly. Of course your can create your own constructors but you need to handle super class constructors properly.

      • Grant Walker

        How would I go about doing that? Is there an example somewhere?

        • Grzegorz Piwowarek

          Well, it’s just about the passing the right params to the super() call in the constructor’s body. I have a feeling you might be asking the wrong question. What are you exactly trying to do?

          • Grant Walker

            When I serialize a User (for example) I need it to be apart of a larger response that includes other key/value pairs. My thoughts are, if I can pass in a map of key/values when serializing a user, my result can look something like this
            Map
            {
            data: user,
            key1: value1,
            key2: value2,
            key2: value3,

            }

  • Mani Kasiviswanathan

    Great article. It helped me very much to custom serialize a Hash table.