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!
Since Jackson 2.2 one might use the converter in JsonSerialize annotation:
@JsonSerialize(converter = OurConverter.class)
and the converter
public class OurConverter extends StdConverter<IN, OUT>
IN and OUT are same class if modifying object
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);
    }
}
                        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