{ "code": 200, "message": "查询成功", "data": [ { "id": 1485178867378401281, "nickname": "测试", "province": null, "city": null, "gender": null, "phone": null, } ] }
当我们返回一个JSON格式的数据时,经常会出现 null 值的这种情况,在实际项目中,我们有可能希望当字段为 null 值时返回 ""
。例如:
{ "code": 200, "data": [ { "birthday": 0, "city": "", "gender": "", "id": 1485178867378401281, "nickname": "测试", "phone": "", } ], "message": "查询成功" }
解决方法:
使用 fastjson 处理 JSON 数据,我们需要自定义实现 WebMvcConfigurationSupport 类,重写其中的 configureMessageConverters 方法
@Configuration public class WebConfig extends WebMvcConfigurationSupport { @Bean public HttpMessageConverter fastJsonMessageConverters() { FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); /* SerializerFeature.PrettyFormat 格式化输出 WriteMapNullValue 输出 map 中值为 null 的字段 WriteNullStringAsEmpty 字符类型字段如果为 null,输出为 ”“ WriteNullNumberAsZero 数值字段如果为 null,输出为 0 WriteNullListAsEmpty List字段如果为 null,输出为[] WriteNullBooleanAsFalse Boolean字段如果为 null,输出为 false DisableCircularReferenceDetect 消除对同一对象循环引用的问题 */ fastJsonConfig.setSerializerFeatures( SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullStringAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullBooleanAsFalse, SerializerFeature.DisableCircularReferenceDetect); fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss"); //将long型转换成字符串输出,防止过长丢失精度 SerializeConfig.getGlobalInstance().put(Long.class, ToStringSerializer.instance); fastJsonConfig.setSerializeConfig(SerializeConfig.globalInstance); fastConverter.setFastJsonConfig(fastJsonConfig); fastConverter.setDefaultCharset(StandardCharsets.UTF_8); List<MediaType> mediaTypeList = new ArrayList<>(); // 解决中文乱码问题,相当于在 Controller上的 @RequestMapping 中加了个属性produces = "application/json" mediaTypeList.add(MediaType.APPLICATION_JSON); fastConverter.setSupportedMediaTypes(mediaTypeList); return fastConverter; } @Override protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) { converters.add(fastJsonMessageConverters()); } }