SpringBoot | Jackson序列化

发布时间 2023-09-27 09:32:33作者: LittleDonkey

欢迎参观我的博客,一个Vue 与 SpringBoot结合的产物:https://poetize.cn

原文链接:https://poetize.cn/article?id=37

依赖

<dependency> 
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0</version>
</dependency>

Jackson注解

  • @JsonProperty("name"):把该属性名称序列化为另外一个名称
  • @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8"):序列化时间为指定格式
  • @JsonIgnore:进行JSON操作时忽略该属性
  • @JsonInclude(JsonInclude.Include.NON_NULL):序列化仅包含非NULL属性

SpringBoot的Json消息转换器

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * MappingJackson2HttpMessageConverter是一个Spring消息转换器,用于在Web应用程序中处理请求和响应内容。
     */
    @Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();

        ObjectMapper objectMapper = new ObjectMapper();

        //设置日期格式
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.setTimeZone(TimeZone.getDefault());

        //所有字段都序列化,包括空、NULL、默认值
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);

        //BigDecimal对象的值将以纯文本形式写入JSON,即不会使用科学计数法或其他格式来表示。
        objectMapper.configure(JsonGenerator.Feature.WRITE_BIGDECIMAL_AS_PLAIN, true);
        //序列化对象为 JSON 时,是否忽略那些在目标 JSON 中没有对应字段名的属性。
        objectMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
        //反序列化(将 JSON 转换为 Java 对象)时,是否在 JSON 中存在但在目标 Java 类中没有相应属性时引发异常。
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        //返回Long转换为String
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        simpleModule.addSerializer(long.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);

        //设置中文编码格式
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON);
        mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);

        return mappingJackson2HttpMessageConverter;
    }
}