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.69k stars 6.51k forks source link

使用JsonField配置日期格式,被FastJsonConfig的全局配置覆盖掉 #1868

Open 201314 opened 6 years ago

201314 commented 6 years ago

1、继承WebMvcConfigurerAdapter后,配置了全局的时间转换格式

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        FastJsonHttpMessageConverter4 jsonConverter = new FastJsonHttpMessageConverter4();
        jsonConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(0, jsonConverter);
        super.extendMessageConverters(converters);
    }

2、使用JSONField指定dto转换时间格式

public class RptMtcTimeOrderCountDTO {
    @JSONField(format = "yyyy-MM-dd")
    private Date statDate;
}

3、最后的转换结果,时间格式为yyyy-MM-dd HH:mm:ss,并不是jsonField的yyyy-MM-dd格式。

4、debug后得到问题在于JSONSerializer类:

    public final void writeWithFormat(Object object, String format) {
        if (object instanceof Date) {
            DateFormat dateFormat = this.getDateFormat();
            if (dateFormat == null) {
                dateFormat = new SimpleDateFormat(format, locale);
                dateFormat.setTimeZone(timeZone);
            }
            String text = dateFormat.format((Date) object);
            out.writeString(text);
            return;
        }

此处的逻辑判断,应该是先判断参数format是否被配置了时间格式,再判断全局时间格式。

zxk175 commented 6 years ago

image 这样可以解决

201314 commented 6 years ago

@zxk175 感觉这样有点取巧

201314 commented 6 years ago

@zxk175 这样操作,全局的配置无法生效,直接给返回long类型。还要每个去配置,贼麻烦。

cxy376700398 commented 5 years ago

我也遇到这个问题了。format值传进去了,但是写死了,优先使用全局设置的dateFormat。很蛋疼。

folochina commented 5 years ago

这个问题应该改吧,正常来说都是从小到大生效的配置

folochina commented 5 years ago

image 这样可以解决

默认就是这个内容 不过spring mvc貌似无效,还是long返回。须每个时间都加@JsonField了,

jqncc commented 5 years ago

问题解决了吗,感觉很久了啊,现在版本还是有