Jackson – Custom Serializer
Last modified: July 22, 2018
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.
Great tutorial. Simple and right to the point. Thank you.
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.
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.
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.
No pressure… Thanks Eugen !
Or maybe it’s a contradiction in goals…
Hi Eugen,
It would be cool if your example here showed one object property as itself being a serialized object.
Cheers,
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.