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?
Perhaps a quick workaround is to add an extra getter on
Item
to returnItemType.name
, and markItemType
getter with@JsonIgnore
?You need to create and use a custom serializer.
To return simple string, you can use default ToStringSerializer without define any extra classes. But you have to define toString() method return this value only.
As OP only wants to serialize one field, you could also use the
@JsonIdentityInfo
and@JsonIdentityReference
annotations:For more info, see How to serialize only the ID of a child with Jackson.
Check out
@JsonValue
annotation.EDIT: like this: