Gson: set date format for timestamp and timezone

Which model should be used for date format 1418805300000-0100? (Timestamp and Time Zone)

GsonBuilder().setDateFormat("?????????????-Z")

Decision:

  • create a new GSON with adapters

    private static Gson createGson(){
    return new GsonBuilder().disableHtmlEscaping()
            .registerTypeHierarchyAdapter(Date.class, new DateTimeSerializer())
            .registerTypeHierarchyAdapter(Date.class, new DateTimeDeserializer())
            .create();
    }
    
    
    public static MyClass fromJson(String json) {
        return createGson().fromJson(json, MyClass.class);
    }
    
    public  String toJson() {
        return createGson().toJson(this);
    }
    
  • JSON Serial Number

    private static class DateTimeSerializer implements JsonSerializer<Date> {
        @Override
        public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
            //  hodgie code
            return new JsonPrimitive(src.getTime() + new SimpleDateFormat("Z").format(src));
        }
    }
    
  • deserializer

    private static class DateTimeDeserializer implements JsonDeserializer<Date> {
    
        @Override
        public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        // hodgie code
        return new Date(Long.valueOf((json).getAsString().substring(0, 13)));
        }
    }
    
+4
source share
1 answer

GsonBuilder#setDateFormat(String)uses Stringas an argument to create instances SimpleDateFormat. SimpleDateFormatdoes not provide templates for creating timestamps. setDateFormatyou cannot achieve what you want. Custom TypeAdapterseems appropriate.

+1
source

Source: https://habr.com/ru/post/1569438/


All Articles