How to serialize ISODate object in Gson?

2k views Asked by At

I have following JSON from mongodb:

{
  "_id" : "123",
  "ip" : "127.0.0.1",
  "start_time" : ISODate("2016-12-28T17:16:08.283Z"),
  "end_ocr_time" : ISODate("2016-12-28T17:16:11.652Z"),
  "end_addr_time" : ISODate("2016-12-28T17:16:12.978Z")
}

In text it looks like

{ "_id" : "D87AFF58-EF20-49E0-AED9-15C5DEF59F9D" , "ip" : "A77K1ARM045" , "start_time" : { "$date" : "2016-12-26T07:03:57.612Z"} , "end_ocr_time" : { "$date" : "2016-12-26T07:04:01.313Z"} , "end_addr_time" : { "$date" : "2016-12-26T07:04:03.524Z"}

Model class:

class DBrecord {

  private String _id;
  private String ip;
  private Date start_time;
  private Date end_ocr_time;
  private Date end_addr_time;

}

I tried:

Gson gson = new Gson();
DBrecord dBrecord = gson.fromJson(cursor.next().toString(), DBrecord.class);

Result:

java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 56 path $.start_time

Also tried to make Gson according to other SO answers:

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

and got:

com.google.gson.JsonParseException: The date should be a string value

Tried to make a deserializer:

GsonBuilder gb = new GsonBuilder();
            gb.registerTypeAdapter(DBrecord.class, new JsonDeserializer<Date>()
            {

                DateFormat format = DateFormat.getInstance();

                @Override
                public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
                        throws JsonParseException
                {
                    try
                    {
                        return format.parse(((JsonObject)json).get("start_time").getAsString());
                    }
                    catch (ParseException e)
                    {
                        throw new JsonParseException(e);
                    }
                }
            });
            Gson gson = gb.create();

and got third type error:

java.lang.UnsupportedOperationException: JsonObject

How this date format — ISODate("2016-12-28T17:16:08.283Z") could be deserialized using Gson?

1

There are 1 answers

3
Paco de la Vega On BEST ANSWER

I checked how JSON looks in Java and it's different from Robomongo as was said in comments. In debug mode JSON string looks like:

{ "_id" : "66800E64-AABF-45A8-BA37-FA9D1FF65EB6" , "ip" : "ALIMKIN-EM9" , "start_time" : { "$date" : "2016-12-22T07:19:42.790Z"} , "end_ocr_time" : { "$date" : "2016-12-22T07:19:48.692Z"} , "end_addr_time" : { "$date" : "2016-12-22T07:19:56.638Z"}}

So I just made class for date:

private ISODate start_time;
private ISODate end_ocr_time;
private ISODate end_addr_time;
private ISODate end_oper_time;
class ISODate {
    private Date $date;
    ISODate() {
        $date = new Date(0);
    }
    public Date get$date() {
        return $date;
    }
}