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

Easter79
• 阅读 848

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

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

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

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

@Configurationpublic 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类
下面是它的官方文档描述:

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.
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
3年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
JS 对象数组Array 根据对象object key的值排序sort,很风骚哦
有个js对象数组varary\{id:1,name:"b"},{id:2,name:"b"}\需求是根据name或者id的值来排序,这里有个风骚的函数函数定义:function keysrt(key,desc) {  return function(a,b){    return desc ? ~~(ak
Wesley13 Wesley13
3年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
ES6 新增的数组的方法
给定一个数组letlist\//wu:武力zhi:智力{id:1,name:'张飞',wu:97,zhi:10},{id:2,name:'诸葛亮',wu:55,zhi:99},{id:3,name:'赵云',wu:97,zhi:66},{id:4,na
Stella981 Stella981
3年前
SpringBoot自定义序列化的使用方式
场景及需求:项目接入了SpringBoot开发,现在需求是服务端接口返回的字段如果为空,那么自动转为空字符串。例如:\    {        "id":1,        "name":null    },    {        "id":2,        "name":"x
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k