Erran Morad
Erran Morad

Reputation: 4743

Make Jackson serializer override specific ignored fields

I have Jackson annotated class like this :

public class MyClass {
   String field1;

   @JsonIgnore
   String field2;

   String field3;

   @JsonIgnore
   String field4;
}

Assume that I cannot change MyClass code. Then, how can I make ObjectMapper override the JsonIgnore for field2 only and serialize it to json ? I want it to ignore field4 though. Is this easy and few lines of code ?

My code for regular serialization :

public String toJson(SomeObject obj){
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = null;
    try {
        json = ow.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return json;
}

Upvotes: 2

Views: 1796

Answers (2)

Michał Ziober
Michał Ziober

Reputation: 38655

You can use MixIn feature:

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.addMixIn(MyClass.class, MyClassMixIn.class);

        System.out.println(mapper.writeValueAsString(new MyClass()));
    }
}

interface MyClassMixIn {

    @JsonProperty
    String getField2();
}

Above code prints:

{
  "field1" : "F1",
  "field2" : "F2",
  "field3" : "F3"
}

Upvotes: 5

sfiss
sfiss

Reputation: 2319

You could use a custom serializer, like so (I leave the refactoring up to you):

private String getJson(final MyClass obj) {
    final ObjectMapper om = new ObjectMapper();
    om.registerModule(new SimpleModule(
            "CustomModule",
            Version.unknownVersion(),
            Collections.emptyMap(),
            Collections.singletonList(new StdSerializer<MyClass>(MyClass.class) {

                @Override
                public void serialize(final MyClass value, final JsonGenerator jgen, final SerializerProvider provider) throws IOException {
                    jgen.writeStartObject();
                    jgen.writeStringField("field1", value.field1);
                    jgen.writeStringField("field2", value.field2);
                    jgen.writeStringField("field3", value.field3);
                    jgen.writeEndObject();
                }

            })));

    try {
        return om.writeValueAsString(obj);
    } catch (final JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}

You can find more information about custom serializers on google/stackoverflow, I think I answered something similar here

Upvotes: 1

Related Questions