2017-03-02 56 views
1

我有一個JSON是somethink像{"Header" : {"name" : "TestData", "contactNumber" : 8019071740}}

如果我插入這對MongoDB的它將會像

{"_id" : ObjectId("58b7e55097989619e4ddb0bb"),"Header" : {"name" : "TestData","contactNumber" : NumberLong(8019071743)}

當我看到這個數據傳回並嘗試使用轉換爲Java對象GSON它拋出異常com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a long but was BEGIN_OBJECT at line 1 column 109 path $.Header.contactNumber

我發現this,但我想知道如果我有非常複雜的JSO n結構,那麼我可能需要在這種方法中操縱許多json節點。

有沒有人有任何更好的替代品。

編輯:1 我讀查詢和轉換JSON如下

Document MongoDocument = mycollection.find(searchCondition); 
String resultJson = MongoDocument.toJson(); 
Gson gson = new Gson(); 
Model model= gson.fromJson(resultJson, ItemList.class); 
+0

您可以在您正在讀取數據的位置添加代碼嗎? – Veeram

+0

添加代碼spinet – Geek

回答

2

蒙戈DB使用BSON格式有自己的類型隨後JSON標準,但它不能被JSON庫沒有解析編寫自定義包裝器/編解碼器。

您可以使用第三方框架/插件來使庫處理文檔和pojo之間的轉換。

如果這不是您的選擇,您將不得不自己繪製。

Document mongoDocument = mycollection.find(searchCondition); 
Model model= new Model(); 
model.setProperty(mongoDocument.get("property"); 
+0

您對這種情況建議使用哪種第三方框架/插件 – Geek

+0

您有許多這樣的代碼。我使用了Morphia和Spring Mongo Db。 – Veeram

+0

所以在這種情況下,我發現使用MongoDB的Java驅動程序存在巨大的缺陷。我這個問題也會出現在Date對象的情況下。 – Geek