3

I'm relatively new to Android dev, coming from an iOS background. Trying to parse my JSON response into a Date object using Retrofit and GSON.

I tried this way with no luck: Retrofit GSON serialize Date from json string into java.util.date

Now , am collecting the response and assigning objects when they are strings correctly, as expected. However when it is a date object the following error is given.

com.google.gson.JsonSyntaxException: 20170502T000000

java.text.ParseException: Failed to parse date ["20170502T000000']: No time zone indicator

I've found a number of different similar questions and answers online, however none seem to do the trick.

MWE of JSON Response

{
    "EventDate": "20170502T000000"
}

JSON Deserializer Class

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class DateDeserializer implements JsonDeserializer<Date> {

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

        SimpleDateFormat format = new
        SimpleDateFormat("yyyyMMdd'T'HHmmss");
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        try {
            return format.parse(date);
        } catch (ParseException exp) {
            return null;
        }
    }
}

GSON Builder

public static final Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://uat.api.net/")
        .addConverterFactory(GsonConverterFactory.create(
                new GsonBuilder()
                        .registerTypeAdapter(Date.class, new DateDeserializer())
                        .create()
                )
        )
        .build();

I've tried to add the 'Z' or Z to the end of the date formatter although it shouldn't matter in this case because the date in the JSON doesn't show a timezone.

Any help would be greatly appreciated

Community
  • 1
  • 1
yorkie1990
  • 181
  • 1
  • 8

0 Answers0