Spring配置@ResponseBody JSON格式
想象一下,我在Spring 3 @Controller中有这个带注释的方法
@RequestMapping("")public @ResponseBody MyObject index(@RequestBody OtherObject obj) {
MyObject result = ...;
return result;
}
但是我需要配置输出json格式,就像我在做的那样:
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);
有什么方法可以配置此行为?
回答:
这是我最终所做的。
<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>
我仍然必须弄清楚如何配置其他属性,例如:
om.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
以上是 Spring配置@ResponseBody JSON格式 的全部内容, 来源链接: utcz.com/qa/420146.html