【问题标题】:Jackson How to retrieve parent bean in a custom Serializer/DeserializerJackson 如何在自定义序列化器/反序列化器中检索父 bean
【发布时间】:2015-06-03 13:29:20
【问题描述】:

在自定义序列化器/反序列化器中,有没有办法检索字段的父 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 中引用。

【问题讨论】:

    标签: java json serialization jackson


    【解决方案1】:

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

    【讨论】:

    • 没有我能想到的机制。
    • 不适合我,我在JsonGenerator.getCurrentValue() 上总是得到空值,知道为什么吗?
    • @rbajales 旧版本可能存在差距,所以要确保的一件事是使用最新的补丁 (2.6.4)。自定义序列化器也可能不会设置当前值,因为它取决于序列化器为嵌套类型适当地设置它。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

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

      我通过将父对象设置到子序列化程序实例中,然后在杰克逊调用子序列化程序时访问它来解决这个问题。

      【讨论】:

        猜你喜欢
        • 2011-12-16
        • 2017-09-10
        • 2016-02-13
        • 2011-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-29
        • 1970-01-01
        相关资源
        最近更新 更多