Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MappingJacksonJsonView: ignore fields without using @JsonIgnore

I need to ignore some fields in a POJO because they are being lazy loaded and/or, in some instances, create an infinite recursion (Parent one-to-many Childs, Child many-to-one Parent). My POJO resides in another jar which knows nothing of Jackson, JSON, etc.

How can I effectively tell Jackson ignore these fields without using the annotations? Through configuration would be best.

Thanks

like image 703
Josh Johnson Avatar asked Jan 20 '23 02:01

Josh Johnson


2 Answers

You can write a Custom Serializer and De-Serializer, with Java code, along these lines:

class CustomSerializer extends JsonSerializer<ARow> {
@Override
public Class<ARow> handledType() {
    return ARow.class;
}

public void serialize(ARow value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeStringField("ounc", value.ounces.toLowerCase()); //Do this for all of your relevant properties..
    jgen.writeEndObject();
}

}

and to register this Custom Serializer with Jackson:

ObjectMapper m = new ObjectMapper();
SimpleModule testModule = new SimpleModule("MyModule", new Version(1, 0, 0, null));
testModule.addSerializer(new CustomSerializer());
m.registerModule(testModule);

To set this up with Spring's MappingJacksonJsonView you will need to extend your own ObjectMapper

public class MyCustomObjectMapper extends ObjectMapper {
    public MyCustomObjectMapper() {
        SimpleModule module = new SimpleModule("My Module", new Version(1, 0, 0, "SNAPSHOT"));
        module.addSerializer(new CustomSerializer());
        module.addSerializer(new CustomSerializer2());
        // etc
        this.registerModule(module);
    }
}

Create a bean for it

<bean id="myCustomObjectMapper" class="com.foo.proj.objectmapper.MyCustomObjectMapper"/>

And inject it into your MappingJacksonJsonView

<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
    <property name="objectMapper" ref="myCustomObjectMapper"/>
</bean>
like image 93
Biju Kunjummen Avatar answered Jan 30 '23 20:01

Biju Kunjummen


Aside from custom handlers that were suggested (and which would work), you could also have a look at mix-in annotations (or this wiki page). With those, you can not only use @JsonIgnore, but also @JsonManagedReference/@JsonBackReference, which are designed to retain one-to-one and one-to-many relationships (ignored on serialization, but re-connected on deserialization!).

like image 42
StaxMan Avatar answered Jan 30 '23 18:01

StaxMan