简体   繁体   中英

set Object Mapper SerializationFeature in spring configuration

I want to configure my Jackson (2.7.4) to indent output (pretty print) in my Spring (4.2.6) MVC controllers.

I have controllers that have the @ResponseBody that of course converts to JSON. I am using a context.xml file. I have this so far:

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

I want to set configure(SerializationFeature f, boolean state) of the ObjectMapper like this:

configure(SerializationFeature.INDENT_OUTPUT, TRUE)

How do I do this in my spring context?

You can use Jackson2ObjectMapperFactoryBean to configure ObjectMapper instance

Example

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

Are you looking somthing like this?

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

Below will be CustomObjectMapper

   public class CustomObjectMapper extends ObjectMapper{

    public CustomObjectMapper(SerializationFeature feature,boolean value) {
        this.configure(feature, value);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM