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

和自甴很熟 提交于 2020-01-01 01:13:24

问题


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?


回答1:


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



回答2:


Check out @JsonValue annotation.

EDIT: like this:

class ItemType
{
  @JsonValue
  public String name;

  public int somethingElse;
}



回答3:


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.




回答4:


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




回答5:


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


来源:https://stackoverflow.com/questions/11031110/how-to-instruct-jackson-to-serialize-a-field-inside-an-object-instead-of-the-obj

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!