Spring Boot @ResponseBody 转换 JSON数据时Date 类型处理方法

本文介绍了使用Jackson和FastJson两种方式解析JSON的方法,并详细解释了如何全局和局部配置时间格式,包括在SpringBoot中使用application.property文件进行全局配置,以及在特定属性的get方法上使用注解进行局部配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引用处:

https://blog.youkuaiyun.com/molashaonian/article/details/53025118
https://blog.youkuaiyun.com/henianyou/article/details/81945409

 

  • 解析JSON的方式:

这里一共有两种不同解析方式 Jackson FastJson两种方式

  • Jackson的方式:SpringBoot 默认的json处理是 jackson 也就是对configureMessageConverters 没做配置;

全局配置:

可以在apllication.property加入下面配置就可以了

  #时间戳统一转换 
  spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

    #时区指定

  spring.jackson.time-zone=GMT+8

局部配置:

    可以在指定属性的get方法上加注解的方式

(注意:如果在属性上加,那么会出现响应结果包含该属性大写,小写两个字段,如:Result:{Ao:xxx,ao:xxx} )

@JsonFormat(timezone = “GMT+8”, pattern = “yyyyMMddHHmmss”)
@JsonProperty("Date")  //用来指定该属性的json序列化字段名,比如:不进行首字母小写转换
public Date getDate() {
    return Date;
}

 

  • FastJson的方式:需要更改configureMessageConverters 配置为FasJson

全局配置:

//mvc config 配置类
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

//修改默认转换的配置
@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );

       //此处是全局处理方式
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        fastConverter.setFastJsonConfig(fastJsonConfig);

        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.ALL); // 全部格式
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        converters.add(fastConverter);
    }   
}

局部配置:

@JSONField(format=”yyyyMMdd”)

 private Date createTime;

//如果也出现json响应字段多的问题,那么也加在get方法上

说明:这里如果字段的局部配置和全局都配置了 ,那么最后是以全局转换来的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值