spring - 在使用GsonHttpMessageConverter之前在Spring中配置Gson

标签 spring spring-mvc gson

在构造Gson之前如何配置GsonHttpMessageConverter

我需要使用@Expose并指定日期格式。

最佳答案

(新方法)使用Java Config
扩展WebMvcConfigurerAdapter,或者如果需要更多控制,请使用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;
    }

}
您可以阅读有关customize provided configuration的更多信息。
(旧方法)使用XML配置
在DispatcherServlet上下文中:
<?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>

关于spring - 在使用GsonHttpMessageConverter之前在Spring中配置Gson,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31335146/

相关文章:

java - @ReplaceWithMock 与 @Qualifier

java - GSON从json文件到对象

java - 使用 GSON 将 JSON 文件中的数据解析为 Java 对象

java - Spring Boot 可选的多部分 POST 请求

java - 如何修复 hibernate 配置中的 NPE?

java - 批量插入成功后更新 Kafka 提交偏移量

java - 使用 spring mvc 和 hibernate 在 jsp 上显示图像

java - 从 session 属性创建下拉列表

android - com.google.gson.JsonParseException : Failed parsing JSON source: java. io.BufferedReader 到 Json - 对这个问题感到困惑

java - 用于单个主机/路由的 PoolingHttpClientConnectionManager