Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure objectmapper inside Custom serializer jackson?

I have a CustomSerializer for a particular field written. I call the custom serializer on an ObjectMapper with certain configurations like WRAP_ROOT_VALUE, PropertyNameStrategy, Inclusion.NON_NULL.

Now inside my custom serializer I want all these properties while serializing my custom class except one (WRAP_ROOT_VALUE).

public class CustomSerializer extends JsonSerializer<Object>{

    @Override
    public void serialize(Object obj, JsonGenerator jgen,
            SerializerProvider arg2) throws IOException,
            JsonProcessingException {
//.......
        jgen.writeObject(obj);
//...       
    }

So my obj here gets serialized with root value wrapped which I don't want.

I cannot edit my POJO for some reason.

How can I disable only a single (or some) property of Objectmapper inside a CustomSerializer ???

like image 836
Siddharth Trikha Avatar asked Dec 24 '22 02:12

Siddharth Trikha


1 Answers

Getting the ObjectMapper

From within a custom JsonSerializer, you can get the ObjectMapper using:

ObjectMapper mapper = ((ObjectMapper) jgen.getCodec());

Setting the ObjectMapper

You also can define a new ObjectMapper within your custom JsonSerializer using:

ObjectMapper mapper = new ObjectMapper();
jgen.setCodec(mapper);
like image 184
cassiomolin Avatar answered Dec 28 '22 08:12

cassiomolin