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
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>
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!).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With