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

时间:2017-01-09 15:44:24

标签: java json mongodb gson isodate

我从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 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”)进行反序列化?

1 个答案:

答案 0 :(得分:1)

我检查了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"}}

所以我刚刚上课了日期:

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