gpt4 book ai didi

java - 通过字段进行 jackson 多态反序列化

转载 作者:行者123 更新时间:2023-12-04 14:55:03 27 4
gpt4 key购买 nike

比方说,我有一个类

public class A{
private UUID typeId;
private B data;
}

public abstract class B{
private String a;
}

public class BChildOne extends B{
... some variables
}

public class BChildTwo extends B{
... some variables
}

B类的type根据A的typeId在变化,所以如果A的typeId为“XXX”,则数据字段的类型为BChildOne,如果A的typeId为“YYY”,则数据字段的类型为BChildTwo。

我怎样才能做到这一点?

所以我试过了;
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility =
JsonAutoDetect.Visibility.NONE, setterVisibility =
JsonAutoDetect.Visibility.NONE)
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include =
JsonTypeInfo.As.EXTERNAL_PROPERTY , property = "typeId")
@JsonSubTypes({
@JsonSubTypes.Type(value = BChildOne.class, name = "40ad2fe6-e672-4f0e-
986e-
619c7a1a3223") }
)
public abstract class B{

但我遇到了以下错误;

Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'typeId' that is to contain type id (for class B)



这是显而易见的,因为 typeId 字段在 A 类而不是 B 类中。

最佳答案

假设你的 JSON 文档是这样的:

{
"type": "foo",
"data": {
"someCommonProperty": "common property",
"fooProperty": "foo specific property"
}
}

{
"type": "bar",
"data": {
"someCommonProperty": "common property",
"barProperty": "bar specific property"
}
}

您可以使用:

public class Wrapper {

private String type;

@JsonTypeInfo(use = Id.NAME, property = "type", include = As.EXTERNAL_PROPERTY)
@JsonSubTypes(value = {
@JsonSubTypes.Type(value = Foo.class, name = "foo"),
@JsonSubTypes.Type(value = Bar.class, name = "bar")
})
private AbstractData data;

// Getters and setters
}

public abstract class AbstractData {

private String someCommonProperty;

// Getters and setters
}

public class Foo extends AbstractData {

private String fooProperty;

// Getters and setters
}

public class Bar extends AbstractData {

private String barProperty;

// Getters and setters
}

在这种方法中, @JsonTypeInfo 设置为使用 type作为 external property确定正确的类来映射 data属性(property)。 JSON 文档可以反序列化如下:

ObjectMapper mapper = new ObjectMapper();
Wrapper wrapper = mapper.readValue(json, Wrapper.class);

关于java - 通过字段进行 jackson 多态反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51018823/

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