Elad Benda2 Elad Benda2 - 13 days ago 10x
JSON Question

gson fails to parse using GsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")

I get this string from the server:

"title":"spoil the ones u love today",
"title":"home made patisserie",

and I try to parse it an object

public class Offer implements Serializable {

public String title;
public Date startDateTime;

Type collectionType = new TypeToken<ArrayList<Offer>>() {

mOffersList.addAll((Collection<? extends Offer>) gson
.fromJson(result, collectionType));

but when I define "startDate" as a Date

the collection I get back from gson is empty

When i define "startDate" as a String

the collection is filled correctly.

I want to change its date format. That's why I prefer saving it as a Date object.

I have tried

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

and yet Gson fails to parse the server's string into

Date startDateTime
. Nothing is added to the
and it stays empty.

What am I doing wrong?


Only setting the required DateFormat is not sufficient.

You need to define an implementation of com.google.gson.JsonDeserializer. For ex.

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class DateDeserializer implements JsonDeserializer<Date> {

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

      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

      try {
          return format.parse(date);
      } catch (ParseException exp) {
          System.err.println("Failed to parse Date:", exp);
          return null;

and then register the above deserializer:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer());