【问题标题】:Jackson Annotation decide on one field class based on another fieldJackson Annotation 根据另一个字段决定一个字段类
【发布时间】:2019-07-23 15:35:05
【问题描述】:

我有多个 AbstractAsset 类的实现

我想根据 type 选择资产 impl。 我设法通过继承和

@JsonSubTypes

问题是,在一对资产中,我已经拥有相同的类型字符串,这使得它

@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type")
@JsonSubTypes({
  @JsonSubTypes.Type(value = TitleAssetDTO.class, name = "TITLE"),
  @JsonSubTypes.Type(value = VideoAssetDTO.class, name = "VIDEO"),
  @JsonSubTypes.Type(value = ImageAssetDTO.class, name = "IMAGE"),
  @JsonSubTypes.Type(value = DataAssetDTO.class, name = "DATA")
})
@AllArgsConstructor
@NoArgsConstructor
public abstract class AbstractAssetDTO {
  @NotNull private String type;
  @NotNull private String key;
}

例如

public class TitleAssetDTO extends AbstractAssetDTO {

  private Title title;

  public Title getTitle() {
    return title;
  }

  public void setTitle(Title title) {
    this.title = title;
  }

  public TitleAssetDTO() {
    this.title = new Title();
  }

  @Data
  public class Title {
    private Integer maxLength;
  }

  @JsonIgnore
  public int getMaxLength() {
    return title.maxLength;
  }
}

问题是其他资产类型作为它们在 json 中的类型字符串,所以我认为使用继承不是解决这个问题的正确方法,复合如下:

class myClass{ 
String type;
AbstractAsset asset;
}

这将是一个更好的实现方式,我该怎么做?

【问题讨论】:

  • 你能创建一个简单的例子吗?什么不起作用以及如何重现它? myClass 有什么问题吗?如果asset 已经有type 并且您不需要复制它,为什么要添加type

标签: java jackson


【解决方案1】:

如果我理解正确,您与type 字段存在名称冲突。然后只需为类型 prop 使用不同的名称: @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "@type")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-12
    • 2011-09-20
    相关资源
    最近更新 更多