gpt4 book ai didi

java - 使用 Jackson 通过 @JsonUnwrapped 反序列化多态类型

转载 作者:行者123 更新时间:2023-12-01 19:38:43 29 4
gpt4 key购买 nike

我想做什么

我想使用 Jackson 反序列化多态类型,使用标准 @JsonTypeInfo 注释,如下所示:

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

Class A implements Base {
public String identifier = "A";
}

Class B implements Base {
public String identifier = "B";
}

Class Decorated {
public String decoration = "DECORATION";

@JsonUnwrapped
public Base base;
}

/*
Serialized instance of Decorated WITHOUT @JsonUnwrapped:
{
"decoration" : "DECORATION",
"base" : {
"identifier" : "A"
}
}

Serialized instance of Decorated WITH @JsonUnwrapped:
{
"decoration" : "DECORATION",
"identifier" : "A"
}
*/

相关帖子:Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

jackson 通常可以将其反序列化,如下所示:

public Object deserialize(String body, Class clazz) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(body, clazz);
}

(如果删除 @JsonUnwrapped 注释,这将起作用)

<小时/>

问题

多态类型与 Jackson 的 @JsonUnwrapped 注释不能很好地配合,正如 2012 年 Jira 票证中所讨论的那样:

http://markmail.org/message/pogcetxja6goycws#query:+page:1+mid:pogcetxja6goycws+state:results

Handle polymorphic types with @JsonUnwrapped

Agreed - while fixing things is obviously preferable, improving error messages would be useful if that can't be done.

Unwrapping is one of features where implementations gets complicated enough that any bugs cropping up (on deserialization esp) tend to be antibiotic-resistant...

很难令人鼓舞。

三年后:

http://markmail.org/message/cyeyc2ousjp72lh3

Handle polymorphic types with @JsonUnwrapped

Resolution: Won't Fix

该死。

那么,有没有什么方法可以诱使 Jackson 给我这种行为,而无需修改 deserialize() 或删除 @JsonUnwrapped 注释?

最佳答案

我的 SinglePolyUnwrappedDeserializer 来自 this Gist可以处理单个多态 @JsonUnwrapped 属性。它采用 Kotlin 语言,但如果需要,可以轻松移植到 Java。示例:

@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type"
)
@JsonSubTypes(
JsonSubTypes.Type(value = A::class, name = "a"),
JsonSubTypes.Type(value = B::class, name = "b")
)
abstract class Base

data class A(val x: Int) : Base()

data class B(val y: Boolean) : Base()

@JsonDeserialize(using = SinglePolyUnwrappedDeserializer::class)
data class C(val a: String, @JsonUnwrapped val b: Base)

据我所知,支持其他注释的所有组合。唯一的限制是只有一个 @JsonUnwrapped 属性。

如果您还需要多态@JsonUnwrapped的通用序列化器,您可以非常轻松地自己编写它,无需任何反射或内省(introspection):只需合并内部对象的ObjectNode到包含对象的 ObjectNode 上。

关于java - 使用 Jackson 通过 @JsonUnwrapped 反序列化多态类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37423848/

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