該文章為原創(chuàng)(轉(zhuǎn)載請(qǐng)注明出處):Fastjson 數(shù)字類(lèi)型轉(zhuǎn)Date,如何使其不識(shí)別為long時(shí)間戳而識(shí)別為字符串 - 簡(jiǎn)書(shū) (jianshu.com)
真實(shí)業(yè)務(wù)場(chǎng)景
例如對(duì)接接口的傳輸數(shù)據(jù)為
{
"date": 20221109
}
接收的類(lèi)為
@Data
public static class Test {
@JSONField(format = "yyyy-MM-dd")
private Date date;
}
使用Fastjson的@JSONField 時(shí) 數(shù)字類(lèi)型數(shù)據(jù)會(huì)識(shí)別為long類(lèi)型的時(shí)間戳,導(dǎo)致數(shù)據(jù)反序列化異常
對(duì)接的接口短期無(wú)法修改,需要做兼容。
需要達(dá)成目的
傳輸?shù)膁ate 字段能夠成功轉(zhuǎn)換為Date
方案
自定義反序列化器,在字段的注解 @JSONField上指定
@Data
public static class Test {
@JSONField(format = "yyyy-MM-dd", deserializeUsing = NumberStringDateCodec)
private Date date;
}
自定義的數(shù)字類(lèi)型轉(zhuǎn)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);
}
}
獲取數(shù)字字符串的值,前后手動(dòng)拼接引號(hào),方法走入到原有的轉(zhuǎn)換邏輯即可。
最終效果
"date": 20221109 成功識(shí)別為Date類(lèi)型對(duì)象
該文章為原創(chuàng)(轉(zhuǎn)載請(qǐng)注明出處):Fastjson 數(shù)字類(lèi)型轉(zhuǎn)Date,如何使其不識(shí)別為long時(shí)間戳而識(shí)別為字符串 - 簡(jiǎn)書(shū) (jianshu.com)