简体   繁体   English

使用Gson在java中将LocalDateTime序列化和反序列化为RFC 3339格式的JSON

[英]Serializing and deserializing LocalDateTime into JSON in RFC 3339 format in java with Gson

I am currently trying to store some database objects which contain timestamps into a graphical database (dgraph).我目前正在尝试将一些包含时间戳的数据库对象存储到图形数据库 (dgraph) 中。 I would like to use JSON to easily take date and time information and store it in a datetime node in the graph, but the graph will only accept data that is formatted in RFC 3339 format with an optional timezone (ex 2006-01-02T15:04:05.999999999 ).我想使用 JSON 轻松获取日期和时间信息并将其存储在图中的日期时间节点中,但该图仅接受以RFC 3339格式格式化并带有可选时区的数据(例如2006-01-02T15:04:05.999999999 )。

I have been using Gson to serialize and de-serialize and other data types work fine, but trying to query the dates returns null .我一直在使用 Gson 进行序列化和反序列化,其他数据类型工作正常,但尝试查询日期返回null I have tried using setDateFormat but that doesn't seem to change anything.我试过使用setDateFormat但这似乎没有改变任何东西。 I currently have the timestamps stored in a LocalDateTime class, but can change that if need be.我目前将时间戳存储在LocalDateTime类中,但可以根据需要进行更改。

How can I force Gson to use the correct format with my timestamps?如何强制 Gson 对我的时间戳使用正确的格式? It currently puts them in this format它目前将它们置于这种格式

"start":{
  "date":{"year":2011,"month":1,"day":2},
  "time":{"hour":10,"minute":4,"second":0,"nano":0}
}

I'm new to serializing and JSON in general so any pointers would be appreciated.我是序列化和 JSON 的新手,所以任何指针都将不胜感激。

I've realized that gson seems to be separating my timestamp into two separate data chunks, How can I force it to keep them together in the correct format?我已经意识到 gson 似乎将我的时间戳分成两个单独的数据块,我如何强制它以正确的格式将它们保存在一起? Do I need a type adapter?我需要类型适配器吗? (I don't know how they work) (我不知道他们是如何工作的)

If you're fine with using a library, Joda Time offers a simple solution:如果您对使用库没问题, Joda Time提供了一个简单的解决方案:

Serialization序列化

DateTime dt = new DateTime(2006, 1, 2, 15, 4, 5, 999, DateTimeZone.UTC);
System.out.println(dt);

-------- OUTPUT --------
2006-01-02T15:04:05.999Z

Deserialization反序列化

DateTime dt = DateTime.parse("2006-01-02T15:04:05.999Z");
System.out.println(dt);

-------- OUTPUT --------
2006-01-02T15:04:05.999Z

As for the standard lib: When dealing with time zones, you'd use ZonedDateTime rather than LocalDateTime .至于标准库:处理时区时,您将使用ZonedDateTime而不是LocalDateTime

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM