Spring Boot 2
在application.yml中
http:
converters:
preferred-json-mapper: gson
现在我用自定义设置编写类Gson
:
public class GsonUtil {
public static GsonBuilder gsonbuilder = new GsonBuilder();
public static Gson gson;
public static JsonParser parser = new JsonParser();
static {
// @Exclude -> to exclude specific field when serialize/deserilaize
gsonbuilder.addSerializationExclusionStrategy(new ExclusionStrategy() {
@Override
public boolean shouldSkipField(FieldAttributes field) {
return field.getAnnotation(Exclude.class) != null;
}
@Override
public boolean shouldSkipClass(Class<?> clazz) {
return false;
}
});
gsonbuilder.setPrettyPrinting();
gson = gsonbuilder.create();
}
}
我如何配置Spring Boot
按照我的习惯Gson
对象来自GsonUtil
?
您需要注册org.springframework.http.converter.json.GsonHttpMessageConverter
转换器在后台处理序列化和反序列化。您可以通过以下方式做到这一点:
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
@EnableWebMvc
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
//You can provide your custom `Gson` object.
converters.add(new GsonHttpMessageConverter(GsonUtil.gson));
}
}
如果您想保留默认的转换器列表,您也可以使用extendMessageConverters
方法而不是configureMessageConverters
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)