如何在 Gson 中序列化 ISODate 对象?

How to serialize ISODate object in Gson?

我关注 mongodb 的 JSON:

{
  "_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")
}

在文本中看起来像

{ "_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"}

型号class:

class DBrecord {

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

}

我试过了:

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

结果:

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

也尝试根据其他SO答案制作Gson:

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

并得到:

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

试图制作反序列化器:

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();

出现第三种错误:

java.lang.UnsupportedOperationException: JsonObject

如何使用 Gson 反序列化这种日期格式 — ISODate("2016-12-28T17:16:08.283Z")?

我检查了 JSON 在 Java 中的外观,它与评论中所说的 Robomongo 不同。在调试模式下 JSON 字符串看起来像:

{ "_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"}}

所以我刚刚 class 日期:

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;
    }
}