Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 465
Ranhiru Jude Cooray Avatar asked Jun 14 '12 10:06

Ranhiru Jude Cooray


People also ask

How do you tell Jackson to ignore a field during serialization?

If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.

How does marking a field as transient makes it possible to serialize an object?

transient doesn't turn off serialization generally, but only for the field with which it's associated. Thus, serializing Foo would not transmit a value for the v3 field.


2 Answers

Check out @JsonValue annotation.

EDIT: like this:

class ItemType {   @JsonValue   public String name;    public int somethingElse; } 
like image 126
StaxMan Avatar answered Sep 23 '22 05:09

StaxMan


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; } 
like image 42
pingw33n Avatar answered Sep 21 '22 05:09

pingw33n