Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configure Gson in Spring before using GsonHttpMessageConverter

How to configure Gson before constructing a GsonHttpMessageConverter?

I need to use @Expose and specify Date format.

like image 410
naXa Avatar asked Jul 10 '15 07:07

naXa


1 Answers

(New Method) Using Java Config

Extend WebMvcConfigurerAdapter or if you need more control use WebMvcConfigurationSupport.

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(createGsonHttpMessageConverter());
        super.configureMessageConverters(converters);
    }

    private GsonHttpMessageConverter createGsonHttpMessageConverter() {
        Gson gson = new GsonBuilder()
                .excludeFieldsWithoutExposeAnnotation()
                .setDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'")
                .create();

        GsonHttpMessageConverter gsonConverter = new GsonHttpMessageConverter();
        gsonConverter.setGson(gson);

        return gsonConverter;
    }

}

You can read more on how to customize provided configuration.

(Old Method) Using XML configuration

In DispatcherServlet context:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="gsonBuilder" class="com.google.gson.GsonBuilder">
        <property name="dateFormat" value="yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'SSS'Z'" />
    </bean>

    <bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="targetObject" ref="gsonBuilder" />
        <property name="targetMethod" value="excludeFieldsWithoutExposeAnnotation" />
    </bean>

    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.json.GsonHttpMessageConverter">
                <property name="gson">
                    <bean class="com.google.gson.Gson" factory-bean="gsonBuilder" factory-method="create" />
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

</beans>
like image 124
naXa Avatar answered Oct 22 '22 22:10

naXa