Thursday, 13 August 2015

Gson, Android retrofit Date format



You need create "DateDeserializer" for mapping json string to Date.  (for api query)

You also need create a "DateSerializer" for convert a Date object to json string.  (for api posting)

Then register them into GsonBuilder.


private Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateDeserializer()).registerTypeAdapter(Date.class, new DateSerializer()).create();



public static String DATE_FORMAT = "yyyy-MM-dd' 'HH:mm:ss.SSS'Z'";

class DateDeserializer implements JsonDeserializer<Date> {

    private static final String TAG = DateDeserializer.class.getSimpleName();

    @Override
    public Date deserialize(JsonElement element, Type arg1, JsonDeserializationContext arg2) throws JsonParseException {
        String date = element.getAsString();

        SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date returnDate = null;
        try {
            returnDate = formatter.parse(date);
        } catch (ParseException e) {
            Log.e(TAG, "Failed to parse dateString: (" + date + "),  due to:", e);
            returnDate =  null;
        }
        return returnDate;
    }
}

class DateSerializer implements JsonSerializer<Date> {

    private static final String TAG = DateSerializer.class.getSimpleName();

    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
        formatter.setTimeZone(TimeZone.getDefault());
        String dateFormatAsString = formatter.format(src);
        return new JsonPrimitive(dateFormatAsString);
    }

}


No comments:

Post a comment