SpringBoot自定義序列化的使用方式--WebMvcConfigurationSupport
阿新 • • 發佈:2018-12-30
場景及需求: 專案接入了SpringBoot開發,現在需求是服務端介面返回的欄位如果為空,那麼自動轉為空字串。
例如:
[
{
"id": 1,
"name": null
},
{
"id": 2,
"name": "xiaohong"
}
]
如上,格式化後的返回內容應該為:
[
{
"id": 1,
"name": ""
},
{
"id": 2,
"name": "xiaohong"
}
]
這裡直接給出解決方案程式碼,這裡支援FastJson和Jackson配置序列化的方式:
@Configuration
public class WebCatMvcConfiguration extends WebMvcConfigurationSupport {
@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(new ToStringSerializer(Long.TYPE));
module.addSerializer(new ToStringSerializer(Long.class));
module.addSerializer(new ToStringSerializer(BigInteger.class));
objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString("");
}
});
objectMapper.registerModule(module);
converter.setObjectMapper(objectMapper);
//這裡是fastJSON的配置方式,更多的內容可以檢視SerializerFeature
// FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
// converter.setFeatures(SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero,
// SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.WriteNullListAsEmpty);
converters.add(converter);
}
}
最後我們也可以瞭解一下:WebMvcConfigurationSupport類
下面是它的官方文件描述:
@EnableWebMvc
to an application@Configuration
class. An alternative more advanced option is to extend directly from this class and override methods as necessary remembering to add@Configuration
@Bean
to overridden @Bean
methods. For more details see the Javadoc of @EnableWebMvc
.
This class registers the following HandlerMapping
s:
RequestMappingHandlerMapping
ordered at 0 for mapping requests to annotated controller methods.HandlerMapping
ordered at 1 to map URL paths directly to view names.BeanNameUrlHandlerMapping
ordered at 2 to map URL paths to controller bean names.HandlerMapping
ordered atInteger.MAX_VALUE-1
to serve static resource requests.HandlerMapping
ordered atInteger.MAX_VALUE
to forward requests to the default servlet.
Note that those beans can be configured with a PathMatchConfigurer
.