简体   繁体   中英

Apply default serializer to properties in custom serializer with Jackson

I have an object that needs serialization, but I've run into a bit of a wall. I needed a custom serializer to serialize differently an invalid object vs a valid one. As such, I wrote a custom serializer that looks like:

public class MySerializer extends JsonSerializer<MyObject> {

    @Override
    public void serialize(MyObject obj, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        if(obj.isValid()){
            jgen.writeObject(obj.getInvalids());
        }
        else{
            jgen.writeObject(obj);
        }
        jgen.writeEndObject();
    }
}

Now I'm getting an error if infinite recursion when I try to serialize (for reasons that are quite clear). So I'm wondering if I can do this without having to change my code to something like:

public class MySerializer extends JsonSerializer<MyObject> {

    @Override
    public void serialize(MyObject obj, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        if(obj.isValid()){
            jgen.writeObject(obj.getInvalids());
        }
        else{
            jgen.writeObjectField("prop1", obj.getProp1());
            jgen.writeObjectField("prop2", obj.getProp2());
            ...
        }
        jgen.writeEndObject();
    }
}

Is there a cleaner way (and less annoying) way to do what I'm trying to do? I've seen this answer to a similar question, but it is quite terse and I was unable to divine a clear solution from it.

The way to get access to "default" serializer (one that Jackson would build if you didn't provide custom one) is by registering a BeanSerializerModifier (use SimpleModule to register it), and then override modifySerializer() . It is given the default serializer, and you can then construct your own, which can then delegate as it sees fit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM