How to instruct Jackson to serialize a field insid

2020-05-30 03:25发布

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?

5条回答
够拽才男人
2楼-- · 2020-05-30 03:36

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

查看更多
相关推荐>>
3楼-- · 2020-05-30 03:38

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;
}
查看更多
forever°为你锁心
4楼-- · 2020-05-30 03:44

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;}
}
查看更多
迷人小祖宗
5楼-- · 2020-05-30 03:45

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.

查看更多
神经病院院长
6楼-- · 2020-05-30 04:01

Check out @JsonValue annotation.

EDIT: like this:

class ItemType
{
  @JsonValue
  public String name;

  public int somethingElse;
}
查看更多
登录 后发表回答