Está precisando trabalhar com Date em JSON e não quer utilizar essa data em String, para isso o GSON pode utilizar um adapter, no código abaixo tem o código da classe do adapter e logo depois o código da instanciação do Gson.
public class GsonUTCDateAdapter implements JsonSerializer<Date>, JsonDeserializer<Date> {
@Override
public JsonElement serialize(Date date, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(getNewDateFormat().format(date));
}
@Override
public Date deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) {
try {
return getNewDateFormat().parse(jsonElement.getAsString());
} catch (ParseException e) {
throw new JsonParseException(e);
}
}
private DateFormat getNewDateFormat() {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault()); //This is the format I need
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); //This is the key line which converts the date to UTC which cannot be accessed with the default serializer
return dateFormat;
}
}
private final Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GsonUTCDateAdapter()).create();
0 comentários