• springboot返回前端对象null转为空字符串


      1  
      2 import com.fasterxml.jackson.core.JsonGenerator;
      3 import com.fasterxml.jackson.core.JsonProcessingException;
      4 import com.fasterxml.jackson.databind.BeanDescription;
      5 import com.fasterxml.jackson.databind.JsonSerializer;
      6 import com.fasterxml.jackson.databind.SerializationConfig;
      7 import com.fasterxml.jackson.databind.SerializerProvider;
      8 import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
      9 import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
     10 import org.apache.commons.lang3.StringUtils;
     11 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
     12  
     13 import java.io.IOException;
     14 import java.util.Collection;
     15 import java.util.List;
     16  
     17  
     18 /**
     19  * 使用官方自带的json格式类库,fastjson因为content type问题时不时控制台报错、无法直接返回二进制等问题
     20  */
     21 class JacksonHttpMessageConverter extends MappingJackson2HttpMessageConverter {
     22  
     23     /**
     24      * 处理数组类型的null值
     25      */
     26     public class NullArrayJsonSerializer extends JsonSerializer<Object> {
     27  
     28         @Override
     29         public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
     30             if (value == null) {
     31                 jgen.writeStartArray();
     32                 jgen.writeEndArray();
     33             }
     34         }
     35     }
     36  
     37  
     38     /**
     39      * 处理字符串类型的null值
     40      */
     41     public class NullStringJsonSerializer extends JsonSerializer<Object> {
     42  
     43         @Override
     44         public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
     45             jsonGenerator.writeString(StringUtils.EMPTY);
     46         }
     47     }
     48  
     49     /**
     50      * 处理数字类型的null值
     51      */
     52     public class NullNumberJsonSerializer extends JsonSerializer<Object> {
     53  
     54         @Override
     55         public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
     56             jsonGenerator.writeNumber(0);
     57         }
     58     }
     59  
     60     /**
     61      * 处理布尔类型的null值
     62      */
     63     public class NullBooleanJsonSerializer extends JsonSerializer<Object> {
     64  
     65         @Override
     66         public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
     67             jsonGenerator.writeBoolean(false);
     68         }
     69     }
     70  
     71  
     72     public class MyBeanSerializerModifier extends BeanSerializerModifier {
     73  
     74  
     75         @Override
     76         public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
     77             //循环所有的beanPropertyWriter
     78             for (Object beanProperty : beanProperties) {
     79                 BeanPropertyWriter writer = (BeanPropertyWriter) beanProperty;
     80                 //判断字段的类型,如果是array,list,set则注册nullSerializer
     81                 if (isArrayType(writer)) {
     82                     //给writer注册一个自己的nullSerializer
     83                     writer.assignNullSerializer(new NullArrayJsonSerializer());
     84                 } else if (isNumberType(writer)) {
     85                     writer.assignNullSerializer(new NullNumberJsonSerializer());
     86                 } else if (isBooleanType(writer)) {
     87                     writer.assignNullSerializer(new NullBooleanJsonSerializer());
     88                 } else if (isStringType(writer)) {
     89                     writer.assignNullSerializer(new NullStringJsonSerializer());
     90                 }
     91             }
     92             return beanProperties;
     93         }
     94  
     95         /**
     96          * 是否是数组
     97          */
     98         private boolean isArrayType(BeanPropertyWriter writer) {
     99             Class<?> clazz = writer.getType().getRawClass();
    100             return clazz.isArray() || Collection.class.isAssignableFrom(clazz);
    101         }
    102  
    103         /**
    104          * 是否是string
    105          */
    106         private boolean isStringType(BeanPropertyWriter writer) {
    107             Class<?> clazz = writer.getType().getRawClass();
    108             return CharSequence.class.isAssignableFrom(clazz) || Character.class.isAssignableFrom(clazz);
    109         }
    110  
    111  
    112         /**
    113          * 是否是int
    114          */
    115         private boolean isNumberType(BeanPropertyWriter writer) {
    116             Class<?> clazz = writer.getType().getRawClass();
    117             return Number.class.isAssignableFrom(clazz);
    118         }
    119  
    120         /**
    121          * 是否是boolean
    122          */
    123         private boolean isBooleanType(BeanPropertyWriter writer) {
    124             Class<?> clazz = writer.getType().getRawClass();
    125             return clazz.equals(Boolean.class);
    126         }
    127  
    128     }
    129  
    130     JacksonHttpMessageConverter() {
    131         getObjectMapper().setSerializerFactory(getObjectMapper().getSerializerFactory().withSerializerModifier(new MyBeanSerializerModifier()));
    132     }
    133  
    134 }

    一定要在下面配置消息转换器,不然没效果

    @Configuration
    public class WebMvcConfig extends WebMvcConfigurationSupport {
        @Override
        protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
            super.configureMessageConverters(converters);
            converters.add(new JacksonHttpMessageConverter());
        }
     
    }
    

    如果想要更丰富的可以在:MyBeanSerializerModifier中自定义。

    原文: https://blog.csdn.net/qq_38132283/article/details/89339817?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-15.baidujs&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-15.baidujs

  • 相关阅读:
    数据仓库--事实表
    Oracle SQL函数pivot、unpivot转置函数实现行转列、列转行
    在Oracle中使用rank()over()排名的问题
    python 有四个数字:1、2、3、4,能组成多少个互不相同且无重复数字的三位数?各是多少? 程序分析:可填在百位、十位、个位的数字都是1、2、3、4。组成所有的排列后再去 掉不满足条件的排列。(用列表推导式)
    pyhton 打印菱形
    三元运算
    Python代码书写规范
    DDT驱动
    使用 JsonPath 完成接口自动化测试中参数关联和数据验证(Python语言)
    数据类型(字典)
  • 原文地址:https://www.cnblogs.com/xuefeilong/p/15429696.html
Copyright © 2020-2023  润新知