日期解析过程中发生异常。

huangapple go评论48阅读模式
英文:

Exception during date parsing

问题

我有一个POJO,在反序列化期间遇到了以下异常。

无法从字符串Jul 17, 2023 12:01:45 PM反序列化到类型为`java.util.Date`的值不是一个有效的表示错误无法解析日期值'Jul 17, 2023 12:01:45 PM':与任何标准形式不兼容(“yyyy-MM-dd'T'HH:mm:ss.SSSX”,“yyyy-MM-dd'T'HH:mm:ss.SSS”,“EEE, dd MMM yyyy HH:mm:ss zzz”,“yyyy-MM-dd”))

POJO

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class B implements Serializable {

@JsonProperty("alarmtime")
Date alarmtime = new Date();
}
ObjectMapper mapper = new ObjectMapper();
B def = mapper.readValue(doc.toString(), B.class);

doc是存储在数据库中或来自第三方API的文档字符串。

有人可以帮助我吗?

英文:

I have a pojo where during deserilization i was getting the following exception.

Cannot deserialize value of type `java.util.Date` from String "Jul 17, 2023 12:01:45 PM": not a valid representation (error: Failed to parse Date value 'Jul 17, 2023 12:01:45 PM': Cannot parse date "Jul 17, 2023 12:01:45 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))

pojo

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class B implements Serializable {

@JsonProperty("alarmtime")
Date alarmtime = new Date();
}
ObjectMapper  mapper = new ObjectMapper();
B def = mapper.readValue(doc.toString(), B.class);

doc is the document string present in the database or from other 3rd party api.

can anyone please help me.

答案1

得分: 2

日期格式与Jackson的默认格式不匹配。在属性上使用JsonFormat.pattern()来指定正确的格式。

@JsonFormat(pattern = "MMM dd, yyyy hh:mm:ss a")

如果可能的话,不要使用过时且容易出错的 DateSimpleDateFormat 等。在Java 8 中,它们被现代的Java日期时间API java.time 取代。

英文:

Format of the date does not match the default format for jackson. Use JsonFormat.pattern() on the property to specify the correct format.

@JsonFormat(pattern = "MMM dd, yyyy hh:mm:ss a")

Also, if possible don't use the outdated and error prone Date, SimpleDateFormat, etc. They were supplanted in java 8 by java.time, the modern java date-time API.

huangapple
  • 本文由 发表于 2023年7月17日 15:20:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76702239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定