Jackson如何在自定义Serializer / Deserializer中检索父bean [英] Jackson How to retrieve parent bean in a custom Serializer/Deserializer
问题描述
在自定义序列化器/反序列化器中,有没有办法检索字段的父bean?
In a custom serializer/deserializer, is there a way to retrieve the parent bean of the field ?
例如:
public class Foo {
@JsonSerialize(using = MyCustomSerializer.class)
public Bar bar;
}
public class Bar {
}
public class MyCustomSerializer extends JsonSerializer<Bar> {
@Override
public void serialize(Bar value, JsonGenerator jgen, SerializerProvider serializers) throws IOException, JsonProcessingException {
// get Foo ??
}
}
这里我想在我的序列化器中获取Foo没有在Bar中有引用。
here I'd like to get Foo in my serializer without to have a reference inside Bar.
推荐答案
如果您使用的是Jackson 2.5,则可以通过<$访问父对象C $ C> JsonGenerator.getCurrentValue()。或者,进一步提升层次结构,通过 getOutputContext()
(具有 getParent()
以及 getCurrentValue()
方法)。
对于自定义反序列化器,也可以通过 JsonParser
获得。
If you are using Jackson 2.5, it is possible to access parent object via JsonGenerator.getCurrentValue()
. Or, further up the hierarchy, going via getOutputContext()
(which has getParent()
as well as getCurrentValue()
method).
This is also available through JsonParser
for custom deserializer.
这篇关于Jackson如何在自定义Serializer / Deserializer中检索父bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!