java springboot 时间格式序列化 UTC8

背景

我们在项目中使用序列化和反序列化组件中,默认一般采用Jackson,如果遇到特殊配置,我们该怎么配置呢,大致有如下两种方式:采用配置文件【application.yml】和代码配置

配置文件

比如添加jackson节点

spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    property-naming-strategy: UPPER_CAMEL_CASE
    sort-properties-alphabetically: true
    mapper:
      ACCEPT_CASE_INSENSITIVE_PROPERTIES: true

属性说明

pring.jackson.date-format指定日期格式,比如yyyy-MM-dd HH:mm:ss,或者具体的格式化类的全限定名
spring.jackson.deserialization是否开启Jackson的反序列化
spring.jackson.generator是否开启json的generators.
spring.jackson.joda-date-time-format指定Joda date/time的格式,比如yyyy-MM-ddHH:mm:ss). 如果没有配置的话,dateformat会作为backup
spring.jackson.locale指定json使用的Locale.
spring.jackson.mapper是否开启Jackson通用的特性.
spring.jackson.parser是否开启jackson的parser特性.
spring.jackson.property-naming-strategy指定PropertyNamingStrategy(CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)或者指定PropertyNamingStrategy子类的全限定类名.
spring.jackson.serialization是否开启jackson的序列化.
spring.jackson.serialization-inclusion指定序列化时属性的inclusion方式,具体查看JsonInclude.Include枚举.
spring.jackson.time-zone指定日期格式化时区,比如America/Los_Angeles或者GMT+10.

FeignClient集成

如果我们在项目中使用了FeignClient,可以指定Mapper,同时也可以进行Jackson的通用配置修改

@Configuration
public class FeignConfig {
    @Bean
    public ObjectMapper jacksonObjectMapper(){
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(JsonGenerator.Feature.IGNORE_UNKNOWN, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES,true);
        return objectMapper;
    }

}

ObjectMapper的设置

ObjectMapper objectMapper = new ObjectMapper();
//去掉默认的时间戳格式     
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//设置为东八区
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
// 设置输入:禁止把POJO中值为null的字段映射到json字符串中
objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
 //空值不序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//反序列化时,属性不存在的兼容处理
objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
//序列化时,日期的统一格式
objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
//序列化日期时以timestamps输出,默认true
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//序列化枚举是以toString()来输出,默认false,即默认以name()来输出
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING,true);
//序列化枚举是以ordinal()来输出,默认false
objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX,false);
//类为空时,不要抛异常
objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//反序列化时,遇到未知属性时是否引起结果失败
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
 //单引号处理
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
//解析器支持解析结束符
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);

你可能感兴趣的:(java,spring,boot,spring)