有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring配置@ResponseBody JSON格式

假设我在Spring3@控制器中有这个带注释的方法

@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);

有没有办法配置此行为

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

  1. spring prefixjson with responsebody
  2. Who sets response content-type in Spring MVC (@ResponseBody)

谢谢大家!


共 (6) 个答案

  1. # 1 楼答案

    适用于Spring版本4.1.3+

    我尝试了Jama的解决方案,但所有的响应都返回了“application/json”内容类型,包括主生成的HTML页面

    重写configureMessageConverters(...)会阻止spring设置默认转换器。Spring 4.1.3允许修改已配置的转换器,方法是覆盖以下内容:

    @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);
        }
    }
    

    see org.springframework..WebMvcConfigurationSupport#getMessageConverters()

    see org.springframework..WebMvcConfigurationSupport#addDefaultHttpMessageConverters(...)

  2. # 2 楼答案

    春天。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>
    
  3. # 3 楼答案

    pointed me移到正确的方向

    这就是我最后做的,以防有人觉得有用

    <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);
    
  4. # 4 楼答案

    我需要解决非常类似的问题,那就是将Jackson Mapper配置为“看在上帝的份上不要序列化空值!!!”

    我不想留下花哨的mvc:annotation-driven标签,所以我找到了如何在不删除mvc:annotation-driven和添加不太花哨的ContentNegotingViewResolver的情况下配置Jackson的ObjectMapper

    最美妙的是,你不必自己编写任何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>
    
  5. # 5 楼答案

    对于使用基于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);
        }
    
    ....
    
    }
    

    我使用的是来自fasterxml的MappingJackson2HttpMessageConverter

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.3.1</version>
    </dependency>
    

    如果你想使用codehaus-jackson映射器,可以使用这个MappingJacksonHttpMessageConverter

     <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>${codehaus.jackson.version}</version>
     </dependency>
    
  6. # 6 楼答案

    我编写了自己的FactoryBean,它实例化了一个ObjectMapper(简化版):

     public class ObjectMapperFactoryBean implements FactoryBean<ObjectMapper>{
    
            @Override
            public ObjectMapper getObject() throws Exception {
                    ObjectMapper mapper = new ObjectMapper();
                    mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
                    return mapper;
            }
    
            @Override
            public Class<?> getObjectType() {
                    return ObjectMapper.class;
            }
    
            @Override
            public boolean isSingleton() {
                    return true;
            }
    
    }
    

    以及spring配置中的用法:

    <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>