gpt4 book ai didi

java - Jackson JsonView 和 JsonTypeInfo

转载 作者:行者123 更新时间:2023-12-02 12:25:37 26 4
gpt4 key购买 nike

我正在使用 JsonTypeInfo 来处理系统读入的一些 JSON 对象的多态性。系统还将这些对象提供给其他服务。在某些情况下,我想要包括类型信息的详细对象,而在其他情况下,我想要对象的准系统最小 View 。

我正在尝试设置 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"; }
}

关于java - Jackson JsonView 和 JsonTypeInfo,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45494420/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com