亲宝软件园·资讯

展开

springboot中用fastjson处理返回值问题详解 springboot中用fastjson处理返回值为null的属性值

King-D 人气:0

我们先来看代码:

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
 public FastJsonHttpMessageConverter fastJsonHttpMessageConverter() {
    FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();

    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    //todo  这里进行配置,空和null,不返回
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    SerializeConfig serializeConfig = SerializeConfig.globalInstance;
    serializeConfig.put(LocalDateTime.class, LocalDateTimeSerializer.instance);
    fastJsonConfig.setSerializeConfig(serializeConfig);

    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.APPLICATION_JSON_UTF8);
    mediaTypeList.add(MediaType.APPLICATION_JSON);
    fastJsonHttpMessageConverter.setSupportedMediaTypes(mediaTypeList);
    fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
    return fastJsonHttpMessageConverter;
  }
}

配置上这个可以在返回的信息中,假如说有null字段的时候,前端不会进行显示这种信息

知识点扩展:

springboot中用fastjson处理返回值为null的属性值

@Bean
  public HttpMessageConverters fastJsonHttpMessageConverters(){
    FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
    FastJsonConfig fastJsonConfig = new FastJsonConfig();
    fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
    fastJsonConfig.setDateFormat("yyyy-MM-dd");
    fastConverter.setFastJsonConfig(fastJsonConfig);
    HttpMessageConverter<?> converter = fastConverter;
    return new HttpMessageConverters(converter);
  }

然后就可以在返回的DTO中使用fastjson的注解,比如

加载全部内容

相关教程
猜你喜欢
用户评论