gpt4 book ai didi

java - 通过 Jackson 的反序列化因父/子类而失败

转载 作者:行者123 更新时间:2023-12-01 21:18:17 29 4
gpt4 key购买 nike

有一个抽象类 Product 和另一个扩展 Product 的类 SomeProduct

产品:

@JsonTypeInfo
(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type"
)
@JsonSubTypes
({
@JsonSubTypes.Type(value = SomeProduct.class, name = Product.PRODUCT_TYPE_SOME)
})
public abstract class Product
{
static final String PRODUCT_TYPE_SOME = "some_product";
}

某些产品:

public class SomeProduct extends Product
{
@JsonProperty("status")
@JsonSerialize(include = JsonSerialize.Inclusion.NON_DEFAULT)
private int status;

public int getStatus()
{
return status;
}

public void setStatus(int status)
{
this.status = status;
}
}

将会有更多的类(不同的产品)扩展Product

当我使用ObjectMapper序列化它时,

ObjectMapper mapper = new ObjectMapper();

Product p = new SomeProduct();
String json = mapper.writeValueAsString(p);

这是输出:

{"type":"some_product"}

现在,当我尝试将其反序列化回来时,

Product x = mapper.convertValue(json, Product.class);

抛出此异常:

java.lang.IllegalArgumentException: Unexpected token (VALUE_STRING), expected FIELD_NAME: missing property 'type' that is to contain type id (for class com.shubham.model.Product) at [Source: N/A; line: -1, column: -1]

我在这里做错了什么?我查看了 SO,发现了一个在 JsonTypeInfo 中使用 defaultImpl 的问题。但我无法将 json 反序列化回“默认 Impl”,因为 JSON 对于特定实现始终有效。

使用 jackson 2.4.3

最佳答案

您错误地使用了mapper.convertValue(json, Product.class);。你应该使用:mapper.readValue(json, Product.class);

convertValue 使用:

Convenience method for doing two-step conversion from given value, into instance of given value type, if (but only if!) conversion is needed. If given value is already of requested type, value is returned as is.

关于java - 通过 Jackson 的反序列化因父/子类而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39574673/

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