agonist_ agonist_ - 11 months ago 85
Java Question

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> {

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 to have a reference inside Bar.

Answer Source

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.