Jude Cooray
Jude Cooray

Reputation: 19872

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?

Upvotes: 35

Views: 20758

Answers (5)

Chenhai-胡晨海
Chenhai-胡晨海

Reputation: 1385

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.

@JsonSerialize(using = ToStringSerializer.class)
class ItemType
{
   String name;
   int somethingElse;
   public String toString(){ return this.name;}
}

Upvotes: 2

Jacob van Lingen
Jacob van Lingen

Reputation: 9567

As OP only wants to serialize one field, you could also use the @JsonIdentityInfo and @JsonIdentityReference annotations:

class Item {
    int id;
    @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="name")
    @JsonIdentityReference(alwaysAsId=true)
    ItemType itemType;
}

For more info, see How to serialize only the ID of a child with Jackson.

Upvotes: 5

StaxMan
StaxMan

Reputation: 116582

Check out @JsonValue annotation.

EDIT: like this:

class ItemType
{
  @JsonValue
  public String name;

  public int somethingElse;
}

Upvotes: 39

pingw33n
pingw33n

Reputation: 12510

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;
}

Upvotes: 24

maksimov
maksimov

Reputation: 5811

Perhaps a quick workaround is to add an extra getter on Item to return ItemType.name, and mark ItemType getter with @JsonIgnore?

Upvotes: 2

Related Questions