我使用MongoD Java Driver存储具有长字段的对象,如下所示:
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();
}
}
由Gson创建的json用于创建我插入的Document(来自第一个println()):
json={"time":1458154511859}
但是当我查阅文档时返回的json如下所示,并且不能由Gson处理(来自第二个println())。
doc json={ "_id" : { "$oid" : "56e9ac0fb032d9320c57bece" }, "time" : { "$numberLong" : "1458154511859" } }
这会在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)
...
显然它可以反序列化$ oid,但不是$ numberLong。那我该如何将这个文件反序列化为WithLong实例呢?感谢