Imagine I have this annotated method in a Spring 3 @Controller
@RequestMapping("")
public @ResponseBody MyObject index(@RequestBody OtherObject obj) {
MyObject result = ...;
return result;
}
But I need to configure the output json format, just as if I were doing:
ObjectMapper om = new ObjectMapper();
om.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
om.getSerializationConfig()
.setSerializationInclusion(JsonSerialize.Inclusion.NON_DEFAULT);
om.getSerializationConfig()
.set(SerializationConfig.Feature.INDENT_OUTPUT, false);
Is there any way to configure this behaviour?
I've found a couple of related questions, but I am not sure about how to adapt them to my specific case:
Thank you !
Doesn't answer the question but this is the top google result.
If anybody comes here and wants do do it for Spring 4 (as it happened to me), you can use the annotation
on the returning class.
I needeed to solve very similar problem, which is configuring Jackson Mapper to "Do not serialize null values for Christ's sake!!!".
I didn't want to leave fancy mvc:annotation-driven tag, so I found, how to configure Jackson's ObjectMapper without removing mvc:annotation-driven and adding not really fancy ContentNegotiatingViewResolver.
The beautiful thing is that you don't have to write any Java code yourself!
And here is the XML configuration (don't be confused with different namespaces of Jackson classes, I simply used new Jakson 2.x library ... the same should also work with Jackson 1.x libraries):
AngerClown pointed me to the right direction.
This is what I finally did, just in case anyone find it useful.
I still have to figure out how to configure the other properties such as:
For the folks who are using Java based Spring configuration:
I'm using
MappingJackson2HttpMessageConverter
- which is from fasterxml.If you want to use codehaus-jackson mapper, instead use this one
MappingJacksonHttpMessageConverter
Yes but what happens if you start using mixins for example, you cant be having ObjectMapper as a singleton because you will be applying the configuration globally. So you will be adding or setting the mixin classes on the same ObjectMapper instance?
Take a look at Rick Hightower's approach. His approach avoids configuring ObjectMapper as a singleton and allows you to filter the JSON response for the same object in different ways per each request method.
http://www.jroller.com/RickHigh/entry/filtering_json_feeds_from_spring