简体   繁体   中英

Jackson JsonView and JSonTypeInfo

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM