Ranhiru Cooray Ranhiru Cooray - 24 days ago 6
Java Question

How to instruct Jackson to serialize a field inside an Object instead of the Object it self?

I have an

Item
class. There's an
itemType
field inside of that class which is of type ItemType.

roughly, something like this.

class Item
{
int id;
ItemType itemType;
}

class ItemType
{
String name;
int somethingElse;
}


When I am serializing an object of type
Item
using Jackson
ObjectMapper
, it serializes the object
ItemType
as a sub-object. Which is expected, but not what I want.

{
"id": 4,
"itemType": {
"name": "Coupon",
"somethingElse": 1
}
}


What I would like to do is to show the
itemType
's
name
field instead when serialized.

Something like below.

{
"id": 4,
"itemType": "Coupon"
}


Is there anyway to instruct Jackson to do so?

Answer

You need to create and use a custom serializer.

public class ItemTypeSerializer extends JsonSerializer<ItemType> 
{
    @Override
    public void serialize(ItemType value, JsonGenerator jgen, 
                    SerializerProvider provider) 
                    throws IOException, JsonProcessingException 
    {
        jgen.writeString(value.name);
    }

}

@JsonSerialize(using = ItemTypeSerializer.class)
class ItemType
{
    String name;
    int somethingElse;
}