A
In my case, I've made a similar task (i.e., like in the sense that in some places, the format of a series of dates has been somewhat different)First, we'll set up a caste-relayer/size date:public class DateSerializer implements JsonSerializer<Date>,JsonDeserializer<Date> {
private static final String TAG=DateSerializer.class.getSimpleName();
private final TimeZone utcTimeZone;
private final DateFormat dateFormat;
private final static String ISO_8601_FORMAT_STRING="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
public DateSerializer() {
dateFormat = new SimpleDateFormat(ISO_8601_FORMAT_STRING, Locale.ENGLISH);
utcTimeZone=TimeZone.getTimeZone("UTC");
dateFormat.setTimeZone(utcTimeZone);
}
@Override public synchronized JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(dateFormat.format(date));
}
@Override
public synchronized Date deserialize(JsonElement jsonElement,Type type,JsonDeserializationContext jsonDeserializationContext) {
Date date;
String[] alternateFormats={
"MMM dd, yyyy HH:mm:ss",
"MMM d, yyyy HH:mm:ss",
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.SSS",
"MMM d, yyyy HH:mm:ss.SSS",
"MMM dd, yyyy HH:mm:ss.SSS"
};
String dateTimeString=jsonElement.getAsString();
MyLogger.info(TAG, "Datetime="+dateTimeString);
DateFormat alternateDateFormat;
try {
date=dateFormat.parse(dateTimeString);
if(date!=null)
return date;
} catch (Exception e) {
//MyLogger.warning(TAG, "Error parsing="+dateTimeString+", format="+ISO_8601_FORMAT_STRING, e);
}
for(String alternateFormat:alternateFormats) {
alternateDateFormat = new SimpleDateFormat(alternateFormat, Locale.ENGLISH);
alternateDateFormat.setTimeZone(utcTimeZone);
try {
date = alternateDateFormat.parse(dateTimeString);
if (date != null)
return date;
}
catch(Exception ex) {
Log.w(TAG, "Error parsing="+dateTimeString+", format="+alternateFormat, ex);
}
}
throw new IllegalArgumentException("Can't parse date/time formatted as="+dateTimeString);
} }
We' put it in gson.gson = new GsonBuilder()
.registerTypeAdapter(Date.class, new DateSerializer())
.serializeNulls()
//.setPrettyPrinting() //for debugging
.disableHtmlEscaping() //http://stackoverflow.com/questions/16558709/gson-issue-with-string
.create();