alibaba / fastjson

FASTJSON 2.0.x has been released, faster and more secure, recommend you upgrade.
https://github.com/alibaba/fastjson2/wiki/fastjson_1_upgrade_cn
Apache License 2.0
25.74k stars 6.5k forks source link

设置fastJsonConfig.setDateFormat("")导致@JSONField(format="")失效 #1968

Open hualunqun opened 6 years ago

hualunqun commented 6 years ago

1、项目采用springmvc方式配置了FastJsonHttpMessageConverter,由于希望默认返回的json数据里面的日期格式为'yyyy-MM-dd HH:mm:ss', 所以设置了fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");,这样正常的对象返回是没问题的,但是经过测试发现,会导致pojo上的注解@JSONField(format="yyyy-MM-dd") 失效。

2、大致看了下JSONSerializer相关的源码,发现好像是代码写死了,但是由于没有太仔细看,不知道有没有遗漏。

xiaojiahuo commented 6 years ago

这个问题存在很长时间了,看了下源码,如果指定了DateFormat会导致字段上的@JSONField(format="yyyy-MM-dd") 失效

public class JSONSerializer extends SerializeFilterable {
...
public final void writeWithFormat(Object object, String format) {
        if (object instanceof Date) {
            DateFormat dateFormat = this.getDateFormat();
            //如果设置了DateFormat,不会进入if
            if (dateFormat == null) {
                dateFormat = new SimpleDateFormat(format, locale);
                dateFormat.setTimeZone(timeZone);
            }
            String text = dateFormat.format((Date) object);
            out.writeString(text);
            return;
        }
}

使用版本:1.2.49

np7sky commented 5 years ago

version 1.2.56, solved? I see add unixtime.

这个问题存在很长时间了,看了下源码,如果指定了DateFormat会导致字段上的@JSONField(format="yyyy-MM-dd") 失效

public class JSONSerializer extends SerializeFilterable {
...
public final void writeWithFormat(Object object, String format) {
        if (object instanceof Date) {
            DateFormat dateFormat = this.getDateFormat();
            //如果设置了DateFormat,不会进入if
            if (dateFormat == null) {
                dateFormat = new SimpleDateFormat(format, locale);
                dateFormat.setTimeZone(timeZone);
            }
            String text = dateFormat.format((Date) object);
            out.writeString(text);
            return;
        }
}

使用版本:1.2.49

np7sky commented 5 years ago

you can try this. https://github.com/alibaba/fastjson/issues/1868#issuecomment-394050639