Escolha uma Página

Gson: conversor Date para formato ISO

Escrito por Alisson

agosto 22, 2023

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();

Você pode gostar…

0 comentários

Enviar um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *