gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 10:17:02 25 4
gpt4 key购买 nike

在构造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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com