title: Parse Date from MongoDB with Gson
body: <p>In my MongoDB a document looks like this:</p>
  
  <pre><code>{ 
  "_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"
  }
  </code></pre>
  
  <p>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:</p>
  
  <p><code>Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 179 path $.timestamp</code></p>
  
  <p>I insert the timestamp into MongoDb via Date too. 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?</p>
  
  <pre><code>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;
  } 
  //...
  </code></pre>
  
  <h2>Edit</h2>
  
  <p>I get the json via the MongoDb Java driver. The error occurs when I want to deserialize the String with gson</p>
  
  <pre><code>public ArrayList&lt;User&gt; findUserByEmail(String email) {
      Gson g = new Gson();
      ArrayList&lt;User&gt; l = new ArrayList&lt;&gt;();
      MongoDatabase db = con.getDatabase("waitinglist");
      MongoCollection col = db.getCollection("users");
  
      MongoCursor&lt;Document&gt; 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;
  }
  </code></pre>
  
  <p>d.toJson() returns </p>
  
  <pre><code>{
  "_id": {
  "$oid": "5613700bc00eac21886b6a51"
  },
  "firstname": "Marc",
  "lastname": "xxxx",
  "email": "marc.xxxxxx@hotmail.com",
  "phone": "+41/12/345678",
  "timestamp": {
     "$date": 1444114443905
   },
  "state": "waiting"
  }
  </code></pre>
  
  <p>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.</p>