I\'m using GSON to serialise some object graphs to JSON. These objects graphs use Joda Time entities (DateTime
, LocalTime
etc).
The top Go
register a TypeAdapter with GSON to wrap the use of a Joda preconfigured Formatters, see http://www.joda.org/joda-time/apidocs/org/joda/time/format/ISODateTimeFormat.html
import java.lang.reflect.Type;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import java.lang.reflect.Type;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
public class JodaDateTimeWithGson {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>(){
@Override
public JsonElement serialize(DateTime json, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(ISODateTimeFormat.dateTime().print(json));
}
})
.create()
;
// Outputs ["20160222T15:58:33.218Z",42,"String"]
System.out.println(gson.toJson(new Object[] {DateTime.now(), 42, "String"}));
}
}
replicate that snippet, a lot of people use different date string formatting thus confusing any library creation.
I used the answers above to do a little helper that will handle both serialization and deserialization for model objects containing DateTime variables.
public static Gson gsonDateTime() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() {
@Override
public JsonElement serialize(DateTime json, Type typeOfSrc, JsonSerializationContext context) {
return new JsonPrimitive(ISODateTimeFormat.dateTime().print(json));
}
})
.registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() {
@Override
public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
DateTime dt = ISODateTimeFormat.dateTime().parseDateTime(json.getAsString());
return dt;
}
})
.create();
return gson;
}
I am using next in my project
public final class DateTimeDeserializer implements JsonDeserializer<DateTime>, JsonSerializer<DateTime>
{
static final org.joda.time.format.DateTimeFormatter DATE_TIME_FORMATTER =
ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
@Override
public DateTime deserialize(final JsonElement je, final Type type,
final JsonDeserializationContext jdc) throws JsonParseException
{
return je.getAsString().length() == 0 ? null : DATE_TIME_FORMATTER.parseDateTime(dateAsString);
}
@Override
public JsonElement serialize(final DateTime src, final Type typeOfSrc,
final JsonSerializationContext context)
{
return new JsonPrimitive(src == null ? StringUtils.EMPTY :DATE_TIME_FORMATTER.print(src));
}
}
It seems to me quite normal that you don't have this kind of library available.
It might look simple at first glance, but the risk is that you end up with a lot of dependencies (some at compile time, some at runtime), and it would not be easy to make sure you don't create unwanted dependencies.
For your case, this should be ok, as I think this is only a runtime dependency (Then a project using the serializerLib should not need JODA lib if JODA is not used). But for some other case, this could become ugly.
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);