Milad Faridnia
Milad Faridnia

Reputation: 9477

How to parse two date formats with Gson

I get this JSON from server :

{
      "Id": 94,
      "RegisteredDate": "2013-09-29T18:46:19Z",
      "EndDate": "2018-08-14T00:00:00"
}

and I try to parse it using this code:

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss").create(); 
JsonParser parser = new JsonParser();

JsonObject jsonObject = parser.parse(response)
                            .getAsJsonObject();

ContractData contractData = gson.fromJson(jsonObject, ContractData.class);

but Gson fails to parse the RegisteredDate from Json so registeredDate is null in my model but endDate seems to be parsed correctly.

Is there a way to correctly parse both of these dates with Gson ?

Upvotes: 0

Views: 1206

Answers (2)

PEHLAJ
PEHLAJ

Reputation: 10126

Try

public class ContractJsonDeSerializer implements JsonDeserializer<Date> {

    public ContractJsonDeSerializer() {
        //Constructor
    }

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            String dateString = json.getAsJsonPrimitive().getAsString();
            if(android.text.TextUtils.isEmpty(dateString)) {
                return null;
            }
            return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(dateString);
        } catch (ParseException e) {
            return new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(dateString);
        }
    }
}

Upvotes: 1

Nouman Ch
Nouman Ch

Reputation: 4121

This custom serializer/deserializer can handle multiple formats. You could first try parsing in one format, then if that fails then try with a second format. This should also handles null dates without blowing up as well.

public class GsonDateDeSerializer implements JsonDeserializer<Date> {

...

private SimpleDateFormat format1 = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
private SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");

...

@Override
public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
    try {
        String j = json.getAsJsonPrimitive().getAsString();
        return parseDate(j);
    } catch (ParseException e) {
        throw new JsonParseException(e.getMessage(), e);
    }
}

private Date parseDate(String dateString) throws ParseException {
    if (dateString != null && dateString.trim().length() > 0) {
        try {
            return format1.parse(dateString);
        } catch (ParseException pe) {
            return format2.parse(dateString);
        }
    } else {
        return null;
    }
}

Hope this will work for you.

Upvotes: 3

Related Questions