Gson to json conversion with two DateFormat

后端 未结 3 1339
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 18:39

My server JSON is returning with two different type of DateFormat. \"MMM dd, yyyy\" and \"MMM dd, yyyy HH:mm:ss\"

When I convert the JSON with the following it is fi

3条回答
  •  日久生厌
    2020-12-02 19:31

    I was facing the same issue. Here is my solution via custom deserialization:

    new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer());
    
    private static final String[] DATE_FORMATS = new String[] {
            "MMM dd, yyyy HH:mm:ss",
            "MMM dd, yyyy"
    };
    
    
    private class DateDeserializer implements JsonDeserializer {
    
        @Override
        public Date deserialize(JsonElement jsonElement, Type typeOF,
                JsonDeserializationContext context) throws JsonParseException {
            for (String format : DATE_FORMATS) {
                try {
                    return new SimpleDateFormat(format, Locale.US).parse(jsonElement.getAsString());
                } catch (ParseException e) {
                }
            }
            throw new JsonParseException("Unparseable date: \"" + jsonElement.getAsString()
                    + "\". Supported formats: " + Arrays.toString(DATE_FORMATS));
        }
    }
    

提交回复
热议问题