Spring配置@ResponseBody JSON格式

Gui*_*ido 39 java spring spring-mvc jackson

想象一下,我在Spring 3 @Controller中有这个带注释的方法

@RequestMapping("")
public @ResponseBody MyObject index(@RequestBody OtherObject obj) {
    MyObject result = ...;
    return result;
}
Run Code Online (Sandbox Code Playgroud)

但我需要配置输出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);
Run Code Online (Sandbox Code Playgroud)

有没有办法配置这种行为?

我发现了几个相关的问题,但我不确定如何使它们适应我的具体情况:

  1. spring responsejson with responsebody
  2. 谁在S​​pring MVC中设置响应内容类型(@ResponseBody)

谢谢 !

Õzb*_*bek 31

对于使用基于Java的Spring配置的人:

@Configuration
@ComponentScan(basePackages = "com.domain.sample")
@EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {
....

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }

....

}
Run Code Online (Sandbox Code Playgroud)

我正在使用MappingJackson2HttpMessageConverter - 来自fastxml.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.3.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

如果你想使用codehaus-jackson mapper,请使用这个 MappingJacksonHttpMessageConverter

 <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>${codehaus.jackson.version}</version>
 </dependency>
Run Code Online (Sandbox Code Playgroud)


小智 28

我需要解决非常类似的问题,即将Jackson Mapper配置为"不要为基督的缘故序列化空值!!!".

我不想留下花哨的mvc:annotation-driven标签,所以我发现,如何配置Jackson的ObjectMapper而不删除mvc:annotation-driven并添加不太真实的ContentNegotiatingViewResolver.

美妙的是你不必自己编写任何Java代码!

这里是XML配置(不要与Jackson类的不同命名空间混淆,我只是使用了新的Jakson 2.x库......同样也应该与Jackson 1.x库一起使用):

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion">
                        <value type="com.fasterxml.jackson.annotation.JsonInclude.Include">NON_NULL</value>
                    </property>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>
Run Code Online (Sandbox Code Playgroud)


Gui*_*ido 15

AngerClown 向我指出了正确的方向.

这是我最终做的,以防万一有人发现它有用.

<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>
Run Code Online (Sandbox Code Playgroud)

我仍然需要弄清楚如何配置其他属性,如:

om.configure(JsonGenerator.Feature.QUOTE_FIELD_NAMES, true);
Run Code Online (Sandbox Code Playgroud)

  • 只是不是这不适用于`<mvc:annotation-driven />`我发现了很难的方法. (2认同)

Tod*_*.Lu 10

:在spring3.2,新的解决方案是通过引入http://static.springsource.org/spring/docs/3.2.0.BUILD-SNAPSHOT/api/org/springframework/http/converter/json/Jackson2ObjectMapperFactoryBean.html中,下面是我的例子:

 <mvc:annotation-driven>
   ?<mvc:message-converters>
     ??<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
       ???<property name="objectMapper">
         ????<bean
 class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
           ?????<property name="featuresToEnable">
             ??????<array>
               ???????<util:constant static-field="com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES" />
             ??????</array>
           ?????</property>
         ????</bean>
       ???</property>
     ??</bean>
   ?</mvc:message-converters>
 </mvc:annotation-driven>
Run Code Online (Sandbox Code Playgroud)


小智 10

对于Spring版本4.1.3+

我尝试了Jama的解决方案,但随后所有的响应都返回了Content-type'application/json',包括主要生成的HTML页面.

覆盖configureMessageConverters(...) 可防止spring设置默认转换器.Spring 4.1.3允许通过覆盖来修改已配置的转换器 extendMessageConverters(...):

@Configuration
public class ConverterConfig extends WebMvcConfigurerAdapter {
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        for (HttpMessageConverter<?> converter : converters) {
            if (converter instanceof AbstractJackson2HttpMessageConverter) {
                AbstractJackson2HttpMessageConverter c = (AbstractJackson2HttpMessageConverter) converter;
                ObjectMapper objectMapper = c.getObjectMapper();
                objectMapper.setSerializationInclusion(Include.NON_NULL);
            }
        }

        super.extendMessageConverters(converters);
    }
}
Run Code Online (Sandbox Code Playgroud)

看到 org.springframework..WebMvcConfigurationSupport#getMessageConverters()

看到 org.springframework..WebMvcConfigurationSupport#addDefaultHttpMessageConverters(...)