更新时间:2022-11-13 22:55:15
在我的应用程序中,我使用以下方法.它根据给定的id
找到一个对象,并通过Gson
对其进行解析并将其保存到相应的对象中.
In my application I use following method. It finds an object according to given id
parses it via Gson
and saves it to corresponding object.
public MyEntity getValue(String id) {
DB db = SessionManager.getInstance().db;
DBCollection collection = db.getCollection("myCollection");
BasicDBObject query = new BasicDBObject("_id", id);
Object object = new Object();
boolean found = false;
DBCursor cursor = collection.find(query);
try {
while (cursor.hasNext()) {
found = true;
String str = (cursor.next().toString());
Gson gson = new Gson();
object = gson.fromJson(str, MyEntity.class);
}
} finally {
cursor.close();
}
if (!found)
return new MyEntity();
MyEntity myEntity = null;
myEntity = (MyEntity) object;
return myEntity;
}