Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 386
Addo Solutions Avatar asked Aug 26 '14 17:08

Addo Solutions


2 Answers

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

like image 68
Andriy Avatar answered Oct 13 '22 13:10

Andriy


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);

    }

}
like image 44
Addo Solutions Avatar answered Oct 13 '22 12:10

Addo Solutions