Created
October 14, 2014 19:03
-
-
Save angelpinheiro/b5cf1d3e4e9c3a1d5a9d to your computer and use it in GitHub Desktop.
Gson ISODateTime serializer/deserializer for Joda DateTime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.gson.JsonDeserializationContext; | |
import com.google.gson.JsonDeserializer; | |
import com.google.gson.JsonElement; | |
import com.google.gson.JsonParseException; | |
import com.google.gson.JsonPrimitive; | |
import com.google.gson.JsonSerializationContext; | |
import com.google.gson.JsonSerializer; | |
import java.lang.reflect.Type; | |
import java.util.Date; | |
import org.joda.time.DateTime; | |
import org.joda.time.format.DateTimeFormatter; | |
public class DateTimeConverter implements JsonSerializer<DateTime>, JsonDeserializer<DateTime> { | |
private DateTimeFormatter fmt; | |
public DateTimeConverter() { | |
fmt = ISODateTimeFormat.dateTimeNoMillis(); | |
} | |
public DateTimeConverter(DateTimeFormatter fmt) { | |
this.fmt = fmt; | |
} | |
@Override | |
public JsonElement serialize(DateTime src, Type srcType, JsonSerializationContext context) { | |
try { | |
return new JsonPrimitive(src.toString(fmt)); | |
} catch (Exception e) { | |
System.out.println(e.getMessage()); | |
} | |
return new JsonPrimitive(""); | |
} | |
@Override | |
public DateTime deserialize(JsonElement json, Type type, JsonDeserializationContext context) | |
throws JsonParseException { | |
try { | |
return fmt.parseDateTime(json.getAsString()); | |
} catch (IllegalArgumentException e) { | |
// May be it came in formatted as a java.util.Date, so try that | |
Date date = context.deserialize(json, Date.class); | |
return new DateTime(date); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment