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
.
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.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With