【发布时间】:2021-08-06 13:28:56
【问题描述】:
在我用 Spring Boot 编写的简单 Web 服务中,我有一个简单的对象,例如:
@Entity
@Table(name = "my_amazing_object", schema="s")
public class MyAmazingObject implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique=true, nullable=false, pecision=10)
private int id;
@Column(name="capture_datetime")
private Date captureDatetime;
public void setCaptureDatetime(Date aCaptureDatetime){
this.captureDatetime = aCaptureDatetime;
}
public Date getCaptureDatetime(){
return this.captureDatetime;
}
}
在我的 Android 应用程序中,我有非常相似的对象,但没有所有这些注释:
public class MyAmazingObject implements Serializable {
private int id;
private Date captureDatetime;
public void setCaptureDatetime(Date aCaptureDatetime){
this.captureDatetime = aCaptureDatetime;
}
public Date getCaptureDatetime(){
return this.captureDatetime;
}
}
我的问题是,当我使用 retrofit2 将此对象发送到 Spring 应用程序时,我遇到了错误
2021-08-06 14:02:03.610 WARN 20440 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Can not deserialize value of type java.util.Date from String "Aug 6, 2021 2:02:03 PM": not a valid representation (error: Failed to parse Date value 'Aug 6, 2021 2:02:03 PM': Can not parse date "Aug 6, 2021 2:02:03 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.Date from String "Aug 6, 2021 2:02:03 PM": not a valid representation (error: Failed to parse Date value 'Aug 6, 2021 2:02:03 PM': Can not parse date "Aug 6, 2021 2:02:03 PM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSZ", "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
at [Source: java.io.PushbackInputStream@f588781; line: 2, column: 22] (through reference chain: com.example.spring.server.entities.MyAmazingObject["captureDatetime"])
我注意到的问题是,在我的 android 应用程序中,当我记录要发送的对象时,我可以看到如下日期时间:
"captureDatetime": "Fri Aug 06 14:02:03 GMT+01:00 2021"
但是在 spring 应用程序中我收到了这样的信息(您可以在错误消息中看到它)
"captureDatetime": "Aug 6, 2021 2:02:03 PM":
我解决了在 android 应用程序中将日期格式化为dd/MM/yyyy HH:mm 之类的字符串并将其发送到 spring 和 spring 服务器上的问题,我必须像这样修改每个 settter(对于 Date):
public void setCaptureDatetime(String aCaptureDatetime){
this.captureDatetime = new SimpleDateFormat("dd/MM/yyyy HH:mm").parse(aCaptureDatetime);
}
它工作正常。但是我知道我的对象有不止一个 Date 并且在我看来,为每个对象添加 SimpleDateFormat 解决方案并不是最好的解决方案,我几乎可以肯定必须有其他方法来做这些事情。
我正在考虑从 android 发送 Date 并在 spring 服务器上保持相同的方式,而不将其解析为正确的格式。
我尝试使用JsonFormat(pattern = "dd/MM/yyyy HH:mm"),但没有帮助。
有什么解决办法吗?
【问题讨论】:
标签: android spring hibernate datetime