MappingJacksonJsonView: ignore fields without using @JsonIgnore

I need to ignore some fields in POJO because they are lazy loaded and / or, in some cases, create infinite recursion (parent "one to many children", "Children-one-one"). My POJO is in another bank that knows nothing about Jackson, JSON, etc.

How can I say that Jackson ignores these fields without using annotations? Through configuration, it would be better.

thanks

+4
source share
2 answers

You can write a custom serializer and de-serializer with Java code in the following 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 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 using Spring MappingJacksonJsonView , you need to expand 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 him

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

And enter it in MappingJacksonJsonView

 <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"> <property name="objectMapper" ref="myCustomObjectMapper"/> </bean> 
+6
source

In addition to the custom handlers that have been proposed (and which will work), you can also see mixing annotations (or this viking page ). With them, you can not only use @JsonIgnore, but also @ JsonManagedReference / @ JsonBackReference, which are designed to preserve one-to-one and one-to-many relationships (ignored during serialization, but connected again during deserialization!).

+3
source

All Articles