Java中的序列化日期 [英] Serializing Date in Java

查看:554
本文介绍了Java中的序列化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过Web服务传递一些对象,其中一些包含java.sql.Date。因为Date没有空的构造函数,它不想被序列化。



问题的第一部分很简单:在客户端和服务之间传递日期的最佳方式是什么?



第二部分有点棘手:一旦我决定如何传递日期,我可以明显地声明日期暂时性,并使一些包装类传递日期为String或其他,但是如何尽可能透明地将相同的解决方案应用于包含Date的几个类? (/)

(我有一个预感,DynamicProxy可能是一个解决方案,但阅读Sun的网站上的文档并不是很有帮助,所以如果真的是这个方向,一些澄清将不胜感激)



编辑:我提出错误的问题,对不起(我和同事之间有些误会,其实是一个问题)。问题出现是因为反序列化。所以,一旦我以xml格式进行日期,它会尝试将其自身反序列化为GregorianCalendar。问题的其他部分仍然存在:接收某些东西(长时间戳或GregorianCalendar)的最佳方法是什么,并将其转换为sql date,而不会为10个不同的类创建10个不同的包装。我正在使用NetBeans代码和wsdl生成。

解决方案

Joda-Time



Date类有一个笨重的API 。更好的实施是 Joda-Time



ISO 8601



Joda-Time还允许您将您的日期转换为 ISO 8601 标准格式(yyyy-mm-ddTHH:MM:SS.SSS)。将日期从服务器移动到其客户端时使用此标准具有将可读格式的完整日期包括在内的优点。当您使用 JAXB 时,日期的XML表示也是这个ISO标准。 (见XMLGregorianCalendar类)


I'm passing around some objects through web service and some of them contain java.sql.Date. Because Date doesn't have empty constructor it doesn't want to get serialized.

First part of a question is easy: what is the best way to pass a date between client and service?

Second part is bit trickier: Once I decide how to pass dates around, I can obviously declare date transient and make some wrapper class to pass dates as String or whatever, but how to apply same solution as transparently as possible to several classes that include Date?

(I have a hunch that DynamicProxy thingy might be a solution, but reading documentation on Sun's site wasn't very helpful, so if it really is something in that direction, some clarification would be appreciated)

Edit: I asked wrong question, sorry (some misunderstanding between me and coworker what is actually a problem). Problem occurs because of deserializing. So once I have date in xml format it tries to deserialize itself as GregorianCalendar. Other part of a question still remains: What is the best way to receive something (long timestamp or GregorianCalendar) and convert it to sql date, without making 10 different wrappers for 10 different classes. I'm using a NetBeans for code and wsdl generation.

解决方案

Joda-Time

The Date class has a clunky API. A better implementation is Joda-Time.

ISO 8601

Joda-Time also allows you to convert your date in a ISO 8601 standard format (yyyy-mm-ddTHH:MM:SS.SSS). Using this standard when moving dates from server to its client has the advantage to include the full date in a readable format. When you use for example JAXB, the XML representation of a date is also this ISO standard. (see the XMLGregorianCalendar class)

这篇关于Java中的序列化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆