gpt4 book ai didi

java - 多级@JsonTypeInfo 和@JsonSubTypes

转载 作者:行者123 更新时间:2023-12-04 08:22:30 25 4
gpt4 key购买 nike

我有类层次结构 A <- B <- C。我不希望类 A 知道 C,所以我打算使用 A.type="B"表示它是类 B,然后是 B.type2 ="C"表示它是 C 类。

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = B.class, name = "B")})
public abstract class A {

private final String type;

public A(String type) {
this.type = type;
}
}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type2")
@JsonSubTypes({@JsonSubTypes.Type(value = C.class, name = "C")})
public class B extends A {

private final String type2;

private final String propertyB;

@JsonCreator
public B(@JsonProperty("type2") String type2,
@JsonProperty("propertyB") String propertyB) {
super("B");
this.type2 = type2;
this.propertyB = propertyB;
}
}

public class C extends B {

private final String propertyC;

@JsonCreator
public C(@JsonProperty("propertyB") String propertyB,
@JsonProperty("propertyC") String propertyC) {
super("C", propertyB);
this.propertyC = propertyC;
}
}
当我将 C 的 JSON 读取到 A 类时,实际的 Java 对象是 B 类而不是 C。
@Test
void whenReadCJsonToA_thenObjectIsInstanceOfC() throws JsonProcessingException {

String json = "{\n" +
" \"type\" : \"B\",\n" +
" \"type2\" : \"C\",\n" +
" \"propertyB\" : \"b\",\n" +
" \"propertyC\" : \"c\"\n" +
"}";

A obj = objectMapper.readValue(json, A.class);
assertTrue(obj instanceof B, "obj is not instance of B"); // pass
assertTrue(obj instanceof C, "obj is not instance of C"); // fail
}
使上述测试通过的一种方法是 writing custom deserializer ,但是如果类包含许多字段,则此解决方案很乏味。
是否有可能以更优雅的方式使上述测试通过?我对级联 @JsonTypeInfo 和 @JsonSubTypes 的缩进是完全错误的吗?
我的 maven 项目可以在 Github 中找到.

最佳答案

根据 this Jackson issue ,仅一种类型鉴别器属性支持多级继承。在我的代码中,只保留属性 type并删除属性 type2 .

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXISTING_PROPERTY, property = "type")
@JsonSubTypes({@JsonSubTypes.Type(value = B.class, name = "B")})
public abstract class A {

private final String type;

public A(String type) {
this.type = type;
}
}

@JsonSubTypes({@JsonSubTypes.Type(value = C.class, name = "C")})
public class B extends A {

private final String propertyB;

@JsonCreator
public B(@JsonProperty("propertyB") String propertyB) {
super("B");
this.propertyB = propertyB;
}
}

public class C extends B {

private final String propertyC;

@JsonCreator
public C(@JsonProperty("propertyB") String propertyB,
@JsonProperty("propertyC") String propertyC) {
super(propertyB);
this.propertyC = propertyC;
}
}
查看完整代码 this commit .
This commit使用枚举作为类型鉴别器属性类型。

关于java - 多级@JsonTypeInfo 和@JsonSubTypes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65432203/

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