美文网首页
Fastjson 数字类型转Date,如何使其不识别为long时

Fastjson 数字类型转Date,如何使其不识别为long时

作者: uhfun | 来源:发表于2022-11-08 17:45 被阅读0次

    该文章为原创(转载请注明出处):Fastjson 数字类型转Date,如何使其不识别为long时间戳而识别为字符串 - 简书 (jianshu.com)

    真实业务场景

    例如对接接口的传输数据为

    {
        "date": 20221109
    }
    

    接收的类为

    @Data
    public static class Test {
        @JSONField(format = "yyyy-MM-dd")
        private Date date;
    }
    

    使用Fastjson的@JSONField 时 数字类型数据会识别为long类型的时间戳,导致数据反序列化异常
    对接的接口短期无法修改,需要做兼容。

    需要达成目的

    传输的date 字段能够成功转换为Date

    方案

    自定义反序列化器,在字段的注解 @JSONField上指定

    @Data
    public static class Test {
        @JSONField(format = "yyyy-MM-dd", deserializeUsing = NumberStringDateCodec)
        private Date date;
    }
    

    自定义的数字类型转Date反序列化器

    public class NumberStringDateCodec extends DateCodec {
    
            @Override
            public <T> T deserialze(DefaultJSONParser parser, Type clazz, Object fieldName, String format, int features) {
                JSONLexer lexer = parser.getLexer();
                if (lexer.token() == JSONToken.LITERAL_INT) {
                    String value = "\"" + lexer.numberString() + "\"";
                    return DateCodec.instance.deserialze(new DefaultJSONParser(value), clazz, null, format, features);
                }
                return super.deserialze(parser, clazz, fieldName, format, features);
            }
        }
    

    获取数字字符串的值,前后手动拼接引号,方法走入到原有的转换逻辑即可。

    最终效果

    "date": 20221109 成功识别为Date类型对象

    该文章为原创(转载请注明出处):Fastjson 数字类型转Date,如何使其不识别为long时间戳而识别为字符串 - 简书 (jianshu.com)

    相关文章

      网友评论

          本文标题:Fastjson 数字类型转Date,如何使其不识别为long时

          本文链接:https://www.haomeiwen.com/subject/irmntdtx.html