Jackson 如何在自定义 Serializer/Deserializer 中检索父 bean

Jackson How to retrieve parent bean in a custom Serializer/Deserializer

在自定义 serializer/deserializer 中,有没有办法检索字段的父 bean?

例如:

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 中引用。

如果您使用的是 Jackson 2.5,则可以通过 JsonGenerator.getCurrentValue() 访问父对象。或者,通过 getOutputContext()(具有 getParent()getCurrentValue() 方法)在层次结构的更上层。 这也可以通过 JsonParser 用于自定义解串器。

注意:如果您使用自定义序列化,getCurrentValue 将为 null

我通过将 parent object 设置到 child 的序列化程序实例中,然后在 child 的序列化程序被调用时访问它来解决这个问题杰克逊.

对于反序列化,您无权访问 JsonGenerator 对象。以下对我有用:

JsonStreamContext parsingContext = jsonParser.getParsingContext();
JsonStreamContext parent = parsingContext.getParent();
Object currentValue = parent.getCurrentValue();