简体   繁体   English

使用Gson从MongoDB解析日期

[英]Parse Date from MongoDB with Gson

In my MongoDB a document looks like this: 在我的MongoDB中,文档如下所示:

{ 
"_id" : ObjectId("5613700bc00eac21886b6a51"), 
"firstname" : "Marc", 
"lastname" : "Anonymous", 
"email" : "marc.XXXXXX@hotmail.com", 
"phone" : "+41/12/345678", 
"timestamp" : ISODate("2015-10-06T06:54:03.905+0000"), 
"state" : "waiting"
}

I am using gson to parse the json into my Java class User which has a variable timestamp and is a Date but I get the following error: 我正在使用gson将json解析为我的Java类User,该类具有可变的时间戳记,并且是Date,但出现以下错误:

Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 179 path $.timestamp

I insert the timestamp into MongoDb via Date too. 我也通过Date将时间戳插入MongoDb。 I don't know how to handle this. 我不知道该如何处理。 Should I just use a String and convert it every time I need in in Date form? 我是否应该只使用String并在需要时以Date形式将其转换?

public class User {

public String firstname;
public String lastname;
public String email;
public String phone;
public Date timestamp;
public String state;

public Date getTimestamp() {
    return timestamp;
}

public void setTimestamp(Date timestamp) {
    this.timestamp = timestamp;
} 
//...

Edit 编辑

I get the json via the MongoDb Java driver. 我通过MongoDb Java驱动程序得到json。 The error occurs when I want to deserialize the String with gson 当我想用gson反序列化String时发生错误

public ArrayList<User> findUserByEmail(String email) {
    Gson g = new Gson();
    ArrayList<User> l = new ArrayList<>();
    MongoDatabase db = con.getDatabase("waitinglist");
    MongoCollection col = db.getCollection("users");

    MongoCursor<Document> f = col.find(eq("email", email)).iterator();
    while (f.hasNext()) {
        Document d = f.next();
        System.out.println(d.toJson());
        l.add(g.fromJson(d.toJson(), User.class));
    }
    return l;
}

d.toJson() returns d.toJson()返回

{
"_id": {
"$oid": "5613700bc00eac21886b6a51"
},
"firstname": "Marc",
"lastname": "xxxx",
"email": "marc.xxxxxx@hotmail.com",
"phone": "+41/12/345678",
"timestamp": {
   "$date": 1444114443905
 },
"state": "waiting"
}

The error is being thrown because the Date gets convertetd into an own document and when I want to deseriazable it with Gson the Json does not fit with my class. 引发错误是因为Date转换为自己的文档,并且当我想用Gson进行反序列化时,Json不适合我的课程。

You can solve this problem by using Jongo and changing your code to the following: 您可以通过使用Jongo并将代码更改为以下内容来解决此问题:

public ArrayList<User> findUserByEmail(String email) {
    Gson g = new Gson();
    ArrayList<User> l = new ArrayList<>();
    Jongo jongo = con.getDB("waitinglist");

    Iterator<User> users = jongo.getCollection("users").find("{email: #}", email).as(User.class).iterator();
    while(users.hasNext()){
        l.add(users.next());
    }
    return l;
}

Otherwise you're going to have to do something like the following... 否则,您将必须执行以下操作...

Make a wrapper class like this 制作这样的包装器类

public static class GsonCompatibleDate {
    @SerializedName("$date")
    public Long date;

    public GsonCompatibleDate(Long date) {
        this.date = date;
    }

    public Date getDate() {
        return new Date(date);
    }

    public void setDate(Date date) {
        this.date = date.getTime();
    }
}
  • Note the annotation @SerializedName("$date") . 注意注释@SerializedName("$date") This just lets you use a nicer Java-style name for your variable; 这只是让您为变量使用一个更好的Java样式名称。

Update your POJO to this or something similar: 将您的POJO更新为此或类似的内容:

public class User {

    public String firstname;
    public String lastname;
    public String email;
    public String phone;
    public GsonCompatibleDate timestamp;
    public String state;

    public Date getTimestamp() {
          return timestamp.getDate();
    }
}

Your de-serialization code would stay exactly as it was before. 反序列化代码将保持原样。 The updated POJO now matches your Mongo JSON output. 更新后的POJO现在与您的Mongo JSON输出匹配。

I tested both methods and they work for me. 我测试了这两种方法,它们对我有用。 I also highly recommend using a library like Jongo, Morphia, etc... instead of using the Mongo driver itself, unless absolutely necessary. 我也强烈建议您使用Jongo,Morphia等库,而不是使用Mongo驱动程序本身,除非绝对必要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM