gpt4 book ai didi

java - 默认类多态性 Jackson Java

转载 作者:行者123 更新时间:2023-12-01 14:05:36 25 4
gpt4 key购买 nike

我正在使用 jackson 的 @JsonTypeInfo 注释来定义反序列化由接口(interface)定义的属性的方法。

我正在使用 include = JsonTypeInfo.As.EXTERNAL_PROPERTY 属性来设置包含在外部对象中的属性。如果未设置该属性,我还使用 defaultImpl 设置故障安全类。

我希望如果 id 丢失,故障回复类用于反序列化参数属性,就像在单元测试中一样:

public class DeserializationTest {
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

public static class OuterClass {
public String id;

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
defaultImpl = InnerImpl.class,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "id"
)
@JsonSubTypes(
@JsonSubTypes.Type(value = InnerImpl2.class, name = "non_default")
)
public Parameters parameters;
}

public interface Parameters {
}

public static class InnerImpl implements Parameters {
public String property;
}

public static class InnerImpl2 implements Parameters {
public String property2;
}

@Test
public void testDeserializationDefault() throws IOException {
OuterClass o = OBJECT_MAPPER.readValue(
"{\"parameters\": {\"property\":\"test\"}, \"id\":\"default\"}", OuterClass.class
);

Assert.assertEquals(InnerImpl.class, o.parameters.getClass());
Assert.assertEquals("test", ((InnerImpl) o.parameters).property);
}

@Test
public void testDeserializationDefaultWithoutId() throws IOException {
OuterClass o = OBJECT_MAPPER.readValue(
"{\"parameters\": {\"property\":\"test\"}}", OuterClass.class
);

Assert.assertEquals(InnerImpl.class, o.parameters.getClass());
Assert.assertEquals("test", ((InnerImpl) o.parameters).property);
}

@Test
public void testDeserializationNonDefault() throws IOException {
OuterClass o = OBJECT_MAPPER.readValue(
"{\"parameters\": {\"property2\":\"test\"}, \"id\":\"non_default\"}", OuterClass.class
);
Assert.assertEquals(InnerImpl2.class, o.parameters.getClass());
Assert.assertEquals("test", ((InnerImpl2) o.parameters).property2);
}
}

但是我在第二次测试时遇到了这个错误:testDeserializationDefaultWithoutId

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.ovh.serving.hub.SerializationTest$InnerImpl` out of VALUE_NULL token
at [Source: (String)"{"parameters": {"storagePath":"storagePathTest"}}"; line: 1, column: 49]

编辑:添加具有特定 id 的用例

EDIT2:如果 id 在内部类中,它与 JsonTypeInfo.As.PROPERTY 一起使用

最佳答案

您要告诉 Jackson 包含一个名为 id 的外部属性,这就是它需要 id 属性的原因。

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXTERNAL_PROPERTY,
property = "id",
defaultImpl = InnerImpl.class
)

@JsonTypeInfo 中删除 includeproperty 它将起作用。你的注释应该是:

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
defaultImpl = InnerImpl.class
)

关于java - 默认类多态性 Jackson Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143929/

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