2017-08-03 88 views
0

我正在使用JsonTypeInfo處理一些JSON對象的多態性,我的系統讀取該對象。系統還將這些對象提供給其他服務。在某些情況下,我想要包括類型信息在內的詳細對象,而在其他情況下,我想讓準系統儘可能少地查看對象。Jackson JsonView和JSonTypeInfo

我試圖設置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; 
} 

回答

1

原來,我以前嘗試使用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"; } 
}