我有一个 json,它类似于 {"Header": {"name": "TestData", "contactNumber": 8019071740}}
如果我将它插入到 mongoDB 中,它将类似于
{“_id”:ObjectId(“58b7e55097989619e4ddb0bb”),“Header”:{“name”:“TestData”,“contactNumber”:NumberLong(8019071743)}
当我读回这些数据并尝试使用 Gson 转换为 java 对象时,它抛出异常 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a long but was BEGIN_OBJECT at line 1 column 109 path $.Header.contactNumber
我找到了 this , 但我想知道如果我有非常复杂的 json 结构那么我可能需要在这种方法中操作许多 json 节点。
有没有人对此有更好的选择。
编辑:1 我正在阅读如下查询和转换 json
Document MongoDocument = mycollection.find(searchCondition);
String resultJson = MongoDocument.toJson();
Gson gson = new Gson();
Model model= gson.fromJson(resultJson, ItemList.class);
最佳答案
我们可以使用下面的代码:
Document doc = documentCursor.next();
JsonWriterSettings relaxed = JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build();
CustomeObject obj = gson.fromJson(doc.toJson(relaxed), CustomeObject.class);
关于java - 转换回 Java 对象时出现 MongoDB "NumberLong/$numberLong"问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42555757/