1

I'm using the MongoD Java Driver to store an object with a long field as follows:

public static class WithLong {
    long time = System.currentTimeMillis();
}

public static void main(String[] args) throws CAAException, InterruptedException {
    MongoClient client = new MongoClient("localhost",27017);
    MongoDatabase db = client.getDatabase("somedb");
    MongoCollection<Document> itemCollection = db.getCollection("mycollection");
    itemCollection.drop();
    itemCollection = db.getCollection("mycollection");

    WithLong rd = new WithLong(); 

    try {
        Gson gson = new Gson();
        String json = gson.toJson(rd);
        System.out.println("json=" + json);
        Document doc = Document.parse(json);
        itemCollection.insertOne(doc);
        String id = doc.get("_id").toString();
        doc = itemCollection.find(new Document().append("_id", new ObjectId(id))).first();
        System.out.println("doc json=" + doc.toJson());
        rd = gson.fromJson(doc.toJson(), WithLong.class);
        System.out.println(rd);
    } finally {
        db.drop();
        client.close();
    }
}

The json created by Gson and that is used to create the Document that I insert is (from the first println()):

json={"time":1458154511859}

but the json that comes back when I look up the doc is as follows and can't be handled by Gson (from the 2nd println()).

doc json={ "_id" : { "$oid" : "56e9ac0fb032d9320c57bece" }, "time" : { "$numberLong" : "1458154511859" } }

This causes the following exception in Gson.fromJson():

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a long but was BEGIN_OBJECT at line 1 column 62
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
at com.google.gson.Gson.fromJson(Gson.java:803)
...

Apparently it can deserialize $oid, but not $numberLong. So how am I supposed to deserialize this Document back into a WithLong instance? Thanks

David Wood
  • 434
  • 1
  • 5
  • 14
  • Related to http://stackoverflow.com/questions/32115005/how-to-deserialize-json-document-obtained-from-mongodb-into-a-pojo-migratin, but no answer there either. – David Wood Aug 05 '16 at 15:55

0 Answers0