How to serialize and deserialize Java 8's java.time types with Gson? [closed]

∥☆過路亽.° 提交于 2019-12-18 03:04:33

问题


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).


回答1:


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);


来源:https://stackoverflow.com/questions/23072733/how-to-serialize-and-deserialize-java-8s-java-time-types-with-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!