Skip to content

SpringBoot 序列化 Json 响应时根据字段名排序

🏷️ Spring Boot Jackson

为使前后端的处理逻辑一致,在返回值序列化时,统一根据字段名的循序排序。

示例代码

同时过滤了值为 null 的字段。

java
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class JacksonConfig {

    @Bean
    JacksonProperties jacksonProperties() {
        JacksonProperties properties = new JacksonProperties();
        properties.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);
        properties.getMapper().put(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);
        properties.getSerialization().put(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
        return properties;
    }

}

参考

  1. springboot 通过 javaconfig 配置 jackson
  2. Jackson ObjectMapper - specify serialization order of object properties