Spring配置@ResponseBody JSON格式 [英] Spring configure @ResponseBody JSON format
本文介绍了Spring配置@ResponseBody JSON格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
想象一下,我在Spring 3 @Controller中有这个带注释的方法
Imagine I have this annotated method in a Spring 3 @Controller
@RequestMapping("")
public @ResponseBody MyObject index(@RequestBody OtherObject obj) {
MyObject result = ...;
return result;
}
但我需要配置输出json格式,就像我在做:
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:
- spring prefixjson with responsebody
- Who sets response content-type in Spring MVC (@ResponseBody)
谢谢!
推荐答案
AngerClown 向我指出了正确的方向。
AngerClown pointed me to the right direction.
这是我最终做的,以防万一有人发现它有用。
This is what I finally did, just in case anyone find it useful.
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
<!-- jackson configuration : https://stackoverflow.com/questions/3661769 -->
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_DEFAULT</value>
</list>
</property>
</bean>
我仍然需要弄清楚如何配置其他属性,例如:
I still have to figure out how to configure the other properties such as:
om.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
这篇关于Spring配置@ResponseBody JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文