如何使用Gson序列化和反序列化Java 8的java.time类型? [英] How to serialize and deserialize Java 8's java.time types with Gson?

查看:226
本文介绍了如何使用Gson序列化和反序列化Java 8的java.time类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用GSON将一些对象图形序列化为JSON。这些对象图使用新的Java 8 java.time 实体( ZonedDateTime OffsetDateTime LocalTime 等)。

我找到了Joda Time serialisers的库这里 - 是否有相当于JDK java.time 类的类库?

此人 a>没有将GSON与 java.time 一起使用的努力付诸于行动 - 他们的问题仍未得到解答)。 >解决方案

这里有一个Java 8库:


https://github.com/gkopff/gson-javatime-serialisers


以下是Maven的详细信息(查看最新版本的核心):

 <依赖性> 
< groupId> com.fatboyindustrial.gson-javatime-serialisers< / groupId>
< artifactId> gson-javatime-serialisers< / artifactId>
< version> 1.1.1< / version>
< /依赖关系>

以下是您如何驾驶它的简单示例:

  Gson gson = Converters.registerOffsetDateTime(new GsonBuilder())。create(); 
SomeContainerObject original = new SomeContainerObject(OffsetDateTime.now());

String json = gson.toJson(original);
SomeContainerObject reconstituted = gson.fromJson(json,SomeContainerObject.class);


I'm using GSON to serialise some object graphs to JSON. These objects graphs use the new Java 8 java.time entities (ZonedDateTime, OffsetDateTime, LocalTime etc).

I've found a library for Joda Time serialisers here - is there an equivalent library for the JDK java.time classes?

(This person had no luck with their efforts to use GSON with java.time - and their question remains unanswered).

解决方案

There's a Java 8 library here:

https://github.com/gkopff/gson-javatime-serialisers

Here's the Maven details (check central for the latest version):

<dependency>
  <groupId>com.fatboyindustrial.gson-javatime-serialisers</groupId>
  <artifactId>gson-javatime-serialisers</artifactId>
  <version>1.1.1</version>
</dependency>

And here's a quick example of how you drive it:

Gson gson = Converters.registerOffsetDateTime(new GsonBuilder()).create();
SomeContainerObject original = new SomeContainerObject(OffsetDateTime.now());

String json = gson.toJson(original);
SomeContainerObject reconstituted = gson.fromJson(json, SomeContainerObject.class);

这篇关于如何使用Gson序列化和反序列化Java 8的java.time类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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