Spring roo 在保存 json 之前无法识别日期格式

发布于 2024-12-19 22:48:02 字数 839 浏览 5 评论 0原文

我在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

傲娇萝莉攻 2024-12-26 22:48:02

您的问题与此非常相关: Spring-roo REST JSON 控制器 mangle日期字段 看一下并确保您在 JSON 反序列化器中使用了正确的 DateTrasformer。例如

new JSONDeserializer()
      .use(Date.class, new DateTransformer("yyyy-MM-dd") )
      .deserialize( people );

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.

new JSONDeserializer()
      .use(Date.class, new DateTransformer("yyyy-MM-dd") )
      .deserialize( people );
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文