[英]Jackson JsonView and JSonTypeInfo
我正在使用JsonTypeInfo處理系統讀取的某些JSON對象上的多態性。系統還將這些對象提供給其他服務。 在某些情況下,我想要詳細的對象,包括類型信息,而在其他情況下,我則希望准系統最小化對象的視圖。
我試圖設置JsonViews來處理此問題,但是無論我做什么,它都將類型信息包含在序列化JSON中。 我嘗試了幾種不同的方法,但以下是我嘗試執行的操作的示例。
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({
@JsonSubTypes.Type(value = PlayerSpawnedEvent.class, name = "PlayerSpawnedEvent"),
@JsonSubTypes.Type(value = PlayerStateChangedEvent.class, name = "EntityStateChangeEvent")
})
public abstract class AbstractEvent
{
@JsonView(Views.Detailed.class)
public String type;
@JsonView(Views.Detailed.class)
public String id;
@JsonView(Views.Minimal.class)
public long time;
}
原來,我以前嘗試使用JsonTypeInfo.As.EXISTING_PROPERTY時無法定義類型。 切換回去,並在每個子類中定義類型。
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type", visible = true)
@JsonSubTypes({
@JsonSubTypes.Type(value = PlayerSpawnedEvent.class, name = "PlayerSpawnedEvent"),
@JsonSubTypes.Type(value = PlayerStateChangedEvent.class, name = "PlayerStateChangedEvent")
})
public abstract class AbstractEvent
{
@JsonView(Views.Detailed.class)
public String type;
@JsonView(Views.Detailed.class)
public String id;
@JsonView(Views.Minimal.class)
public long time;
}
public class PlayerSpawnedEvent
{
public PlayerSpawnedEvent() { type = "PlayerSpawnedEvent"; }
}
public class PlayerStateChangedEvent
{
public PlayerStateChangedEvent() { type = "PlayerStateChangedEvent"; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.