Java 在spring配置中设置对象映射器序列化功能

Java 在spring配置中设置对象映射器序列化功能,java,json,spring,spring-mvc,jackson,Java,Json,Spring,Spring Mvc,Jackson,我想将我的Jackson(2.7.4)配置为在Spring(4.2.6)MVC控制器中缩进输出(漂亮打印) 我有一些控制器带有@ResponseBody,当然可以将其转换为JSON。我使用的是context.xml文件。到目前为止,我有: <mvc:annotation-driven> <mvc:message-converters register-defaults="true"> <bean class="org.springfr

我想将我的Jackson(2.7.4)配置为在Spring(4.2.6)MVC控制器中缩进输出(漂亮打印)

我有一些控制器带有@ResponseBody,当然可以将其转换为JSON。我使用的是context.xml文件。到目前为止,我有:

    <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">
                    <!---  WHAT GOES HERE -->
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

在我的spring环境中如何做到这一点?

你看起来像这样吗

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.kulhade.config.CustomObjectMapper">
                    <constructor-arg type="com.fasterxml.jackson.databind.SerializationFeature" value="INDENT_OUTPUT"/>
                    <constructor-arg type="boolean" value="true"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

您可以使用Jackson2ObjectMapperFactoryBean来配置ObjectMapper实例

范例

<property name="objectMapper">
    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
        p:failOnEmptyBeans="false"
        p:indentOutput="true">
        <!-- Other properties -->
    </bean>
</property>


我收到此错误:Bean属性“featuresToEnable”不可写或具有无效的setter方法。setter的参数类型与getter的返回类型匹配吗?@mmaceachran我已经编辑了代码。请检查。@mmaceachran使用CustomObjectMapper还有另一种方法。由于jackson的ObjectMapper中没有构造函数,我们可以在其中提供构造函数参数,所以我创建了customObjectMapper。我们赢了!
   public class CustomObjectMapper extends ObjectMapper{

    public CustomObjectMapper(SerializationFeature feature,boolean value) {
        this.configure(feature, value);
    }
}
<property name="objectMapper">
    <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean"
        p:failOnEmptyBeans="false"
        p:indentOutput="true">
        <!-- Other properties -->
    </bean>
</property>