Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In a custom serializer/deserializer, is there a way to retrieve the parent bean of the field?

For example:

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 ??
    }
}

Here I'd like to get Foo in my serializer without having to have a reference inside Bar.

like image 566
agonist_ Avatar asked Jun 03 '15 13:06

agonist_


2 Answers

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.

like image 80
StaxMan Avatar answered Nov 07 '22 15:11

StaxMan


For deserialization, where you don't have access to the JsonGenerator object. The following worked for me:

JsonStreamContext parsingContext = jsonParser.getParsingContext();
JsonStreamContext parent = parsingContext.getParent();
Object currentValue = parent.getCurrentValue();
like image 32
pgkelley Avatar answered Nov 07 '22 14:11

pgkelley