springboot返回json的格式化问题

在实际开发过程中,接口的定义和规范,严格意义上会细化到,空字符串应该返回null还是"",亦或是"null",空数组应该返回null还是[],包括是不是要返回value为null的字段。但是springboot默认使用的是Jackson json转换器。Jackson在设置json的格式化问题时虽然可以通过手动重写方法实现,但是不够灵活。因而可以使用阿里的fastjson实现格式的灵活配置,下面介绍两种的具体实现:

一、通过fastjson实现

在Application类下面添加如下代码,将默认的json转换工具替换为fastjson。其中SerializerFeature里面有很多可自行设置的返回样式,可以自行度狗了解。

/**
     * 替换框架json为 FastJson返回
     * 
     * @param
     */
    @Bean
    public HttpMessageConverters configureMessageConverters() {
        // 1.构建了一个HttpMessageConverter FastJson消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        // 2.定义一个配置,设置编码方式,和格式化的形式
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        // 3.设置PrettyFormat格式化,设置空字符,空集合返回空数组[]等
        fastJsonConfig.setSerializerFeatures(
                // 是否格式化返回Json
                SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue, SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullNumberAsZero, SerializerFeature.WriteNullStringAsEmpty);
        // 4.处理中文乱码问题
        List fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);

        // 5.将fastJsonConfig加到消息转换器中
        fastConverter.setFastJsonConfig(fastJsonConfig);
        return new HttpMessageConverters(fastConverter);
    }

二、通过使用JacksonObjectMapper,实现自己的SerializerModifier实现

在Application类下面添加如下代码:

/**
     * 默认返回空json字符串,数组序列化为[]
     *
     * @param builder
     * @return
     */
    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
        ObjectMapper objectMapper = builder.createXmlMapper(false).build();
        // 为mapper注册一个带有SerializerModifier的Factory,此modifier主要做的事情为:当序列化类型为array,list、set时,当值为空时,序列化成[]
        objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new SerializerModifier()));
        // 空值处理为空串
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });

        return objectMapper;
    } 
  

实现自己的SerializerModifier:

package com.walletServer.config;

import java.util.List;
import java.util.Set;
 
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
 
public class SerializerModifier extends BeanSerializerModifier {
 
    private JsonSerializer _nullArrayJsonSerializer = new ArrayJsonSerializer();
 
    @Override
    public List changeProperties(SerializationConfig config, BeanDescription beanDesc,
            List beanProperties) {
        // 循环所有的beanPropertyWriter
        for (int i = 0; i < beanProperties.size(); i++) {
            BeanPropertyWriter writer = beanProperties.get(i);
            // 判断字段的类型,如果是array,list,set则注册nullSerializer
            if (isArrayType(writer)) {
                 //给writer注册一个自己的nullSerializer
                writer.assignNullSerializer(this.defaultNullArrayJsonSerializer());
            }
        }
        return beanProperties;
    }
 
    // 判断是什么类型
    protected boolean isArrayType(BeanPropertyWriter writer) {
        Class clazz = writer.getPropertyType();
        return clazz.isArray() || clazz.equals(List.class) || clazz.equals(Set.class);
 
    }
 
    protected JsonSerializer defaultNullArrayJsonSerializer() {
        return _nullArrayJsonSerializer;
    }
}
 
  

 

package com.walletServer.config;

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class ArrayJsonSerializer extends JsonSerializer {

    @Override
    public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        if (value == null) {
            jgen.writeStartArray();
            jgen.writeEndArray();
        } else {
            jgen.writeObject(value);
        }
    }
}
 
  

 

你可能感兴趣的:(springboot)