首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >SpringBoot自定义序列化的使用方式--WebMvcConfigurationSupport

SpringBoot自定义序列化的使用方式--WebMvcConfigurationSupport

作者头像
一枝花算不算浪漫
发布2018-06-26 14:53:31
发布2018-06-26 14:53:31
1.4K0
举报

场景及需求: 项目接入了SpringBoot开发,现在需求是服务端接口返回的字段如果为空,那么自动转为空字符串。

例如: [      {          "id": 1,          "name": null      },      {          "id": 2,          "name": "xiaohong"      } ]

如上,格式化后的返回内容应该为: [      {          "id": 1,          "name": ""      },      {          "id": 2,          "name": "xiaohong"      } ]

这里直接给出解决方案代码,这里支持FastJson和Jackson配置序列化的方式:

代码语言:javascript
复制
@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);
    }
代码语言:javascript
复制
}

最后我们也可以了解一下:WebMvcConfigurationSupport类 下面是它的官方文档描述:

代码语言:javascript
复制
public class WebMvcConfigurationSupport
extends Object
implements ApplicationContextAware, ServletContextAware

This is the main class providing the configuration behind the MVC Java config. It is typically imported by adding @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 to the subclass and @Bean to overridden @Bean methods. For more details see the Javadoc of @EnableWebMvc.

This class registers the following HandlerMappings:

  • 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 at Integer.MAX_VALUE-1 to serve static resource requests.
  • HandlerMapping ordered at Integer.MAX_VALUE to forward requests to the default servlet.

Registers these HandlerAdapters:

  • RequestMappingHandlerAdapter for processing requests with annotated controller methods.
  • HttpRequestHandlerAdapter for processing requests with HttpRequestHandlers.
  • SimpleControllerHandlerAdapter for processing requests with interface-based Controllers.

Registers a HandlerExceptionResolverComposite with this chain of exception resolvers:

  • ExceptionHandlerExceptionResolver for handling exceptions through @ExceptionHandler methods.
  • ResponseStatusExceptionResolver for exceptions annotated with @ResponseStatus.
  • DefaultHandlerExceptionResolver for resolving known Spring exception types

Registers an AntPathMatcher and a UrlPathHelper to be used by:

  • the RequestMappingHandlerMapping,
  • the HandlerMapping for ViewControllers
  • and the HandlerMapping for serving resources

Note that those beans can be configured with a PathMatchConfigurer.

Both the RequestMappingHandlerAdapter and the ExceptionHandlerExceptionResolver are configured with default instances of the following by default:

  • a ContentNegotiationManager
  • a DefaultFormattingConversionService
  • a OptionalValidatorFactoryBean if a JSR-303 implementation is available on the classpath
  • a range of HttpMessageConverters depending on the third-party libraries available on the classpath.
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-06-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档