Reputation: 695
I am using JsonTypeInfo to handle polymorphism on some JSON objects that my system reads in. The system also provides these objects to other services. In some cases, I want detailed objects including type info and in other case I want barebones minimal views of the objects.
I am attempting to setup JsonViews to handle this, but no matter what I do, it includes the type information in the serialized JSON. I have tried a handful of diffent ways, but below is an example of what I am trying to do.
@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;
}
Upvotes: 0
Views: 548
Reputation: 695
Turns out that I failed to define the types when I tried using JsonTypeInfo.As.EXISTING_PROPERTY previously. Switching it back and also defining the type in each child class worked out.
@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"; }
}
Upvotes: 1