• 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

  • 相关阅读:
    JavaScript 预解析
    JavaScript 作用域
    JavaScript 函数
    SlidesJS
    1. Skippr
    HTML5 模拟现实物理效果
    实现各种 CSS3 文本动画效果
    表单填写进度提示效果
    HTML5 WebGL 实现逼真的云朵效果
    【原创】bootstrap框架的学习 第八课 -[bootstrap表单]
  • 原文地址:https://www.cnblogs.com/xuefeilong/p/15429696.html
Copyright © 2020-2023  润新知