Nitroware Nitroware - 4 months ago 61
Java Question

Jackson JSON Modify Object Before Serialization

I am looking to modify an object right before it gets serialized. I want to write a custom serializer to parse the object, then pass it to the default object serializer.

This is what I have:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;

/**
*
* @author Me
*/
public class PersonSerializer extends JsonSerializer<Person>{

@Override
public void serialize(Person value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {

//This returns a modified clone of Person value.
Person safePerson = PrivacyService.getSafePerson(value);

provider.defaultSerializeValue(safePerson, jgen);

}

}


But that just goes in an infinate loop. I have also tried:

provider.findTypedValueSerializer(Person.class, true, null).serialize(safePerson, jgen, provider);


That works, but it doesn't parse any of the fields in the object.

I also tried using a
@JsonFilter
but it was extremely heavy and sextupled my load times.

Help! Thanks!

Answer

Holy crap, after several hours of digging through this library, trying to write my own factory, and a thousand other things, I FINALLY got this stupid thing to do what I wanted:

public class PersonSerializer extends JsonSerializer<Person>{

    @Override
    public void serialize(Person value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {

        Person safePerson = PrivacyService.getSafePerson(value);

        //This is the crazy one-liner that will save someone a very long time
        BeanSerializerFactory.instance.createSerializer(provider, SimpleType.construct(Person.class)).serialize(safePerson, jgen, provider);

    }

}