Spring roo 在保存 json 之前无法识别日期格式
我在 MySQL 之上使用 Spring Roo。我通过 Roo 生成的 JSON 方法提取日期,在浏览器表单中更改该数据,然后通过 Roo 生成的 JSON 方法将其保存回来。
我得到的日期格式是yyyy-MM-dd
,标准MySQL日期格式。我在浏览器上使用日历小部件来确保我提交的日期格式相同。
不幸的是,我的数据没有直接通过 ...FromJson()
方法,失败并出现错误:
Parsing date 2007-12-12 was not recognized as a date format
我认为问题在于它以字符串形式出现,但 JPA 感觉它需要生成要更新的 Date
对象。
我很乐意展示我的代码,但这并不是 Roo 为我构建的。
我突然想到,当它说“被识别为日期格式”时,它指的是某些东西。有什么地方我可以更改它所知道的日期格式吗?
编辑:在@nowaq的帮助下,这是最终的答案:
public static Lease fromJsonToLease(String json) {
return new JSONDeserializer<Lease>()
.use(null, Lease.class)
.use(Date.class, new DateFormatter("yyyy-MM-dd"))
.deserialize(json);
}
这样 JSONDeserializer 就知道它正在处理哪个类,并为该类中的所有日期构建一个格式化程序。邪恶!
I'm using Spring Roo on top of MySQL. I pull dates out via the Roo-generated JSON methods, make changes to that data in a browser form, and save it back via the Roo-generated JSON methods.
The date format I'm getting out is yyyy-MM-dd
, standard MySQL date format. I'm using a calendaring widget on the browser to ensure the date I'm submitting is the same format.
Unfortunately my data doesn't go right through the ...FromJson()
method, failing with the error:
Parsing date 2007-12-12 was not recognized as a date format
I presume that the problem is that it's coming out as a string, but JPA feels like it needs to generate a Date
object to update.
I'll happily show my code about this, but it's nothing Roo didn't build for me.
It occurs to me that there's something it's referring to when it says "recognized as a date format". Is there somewhere I can change what date formats it knows?
EDIT: With @nowaq's help, here's the ultimate answer:
public static Lease fromJsonToLease(String json) {
return new JSONDeserializer<Lease>()
.use(null, Lease.class)
.use(Date.class, new DateFormatter("yyyy-MM-dd"))
.deserialize(json);
}
That way JSONDeserializer knows what class it's dealing with AND builds a formatter for all the dates in that class. Wicked!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题与此非常相关: Spring-roo REST JSON 控制器 mangle日期字段 看一下并确保您在 JSON 反序列化器中使用了正确的 DateTrasformer。例如
Your question is very related to this one: Spring-roo REST JSON controllers mangle date fields Take a look and make sure you're using correct DateTrasformer(s) with your JSON deserializers. E.g.