I'm using GSON to serialise some object graphs to JSON. These objects graphs use Joda Time entities (DateTime
, LocalTime
etc).
The top Google hit for "gson joda" is this page:
It provides source for a type adapter for org.joda.time.DateTime
. This link is also what is referenced in the GSON User Guide.
I expected to find a pre-rolled library that included joda-time serialisers that I could reference as a Maven dependency - but I can't find one.
Is there one? Or am I forced to replicate that snippet in my own project?
fromJson() constructor, for constructing a new User instance from a map structure. A toJson() method, which converts a User instance into a map.
A Gson is a library for java and it can be used to generate a JSON. We can use the fromJson() method of Gson to parse JSON string into java object and use the toJson() method of Gson to convert Java objects into JSON string.
Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of.
I've decided to roll my own open source one - you can find it here:
https://github.com/gkopff/gson-jodatime-serialisers
Here's the Maven details (check central for the latest version):
<dependency> <groupId>com.fatboyindustrial.gson-jodatime-serialisers</groupId> <artifactId>gson-jodatime-serialisers</artifactId> <version>1.6.0</version> </dependency>
And here's a quick example of how you drive it:
Gson gson = Converters.registerDateTime(new GsonBuilder()).create(); SomeContainerObject original = new SomeContainerObject(new DateTime()); String json = gson.toJson(original); SomeContainerObject reconstituted = gson.fromJson(json, SomeContainerObject.class);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With