我的应用程序使用JSON对象很多(org.json.JSONArray和朋友)。将它们存储到Mongo DBObjects以便查询它们的最有效方法是什么? BasicDBObject无法序列化JSONArray - 这两个层次之间似乎没有互操作性。在MongoDB中使用JSON?
18
A
回答
8
OK似乎没有互操作性,所以我滚动我自己的。繁忙的工作,以绕过类型系统:
public class Util {
public static DBObject encode(JSONArray a) {
BasicDBList result = new BasicDBList();
try {
for (int i = 0; i < a.length(); ++i) {
Object o = a.get(i);
if (o instanceof JSONObject) {
result.add(encode((JSONObject)o));
} else if (o instanceof JSONArray) {
result.add(encode((JSONArray)o));
} else {
result.add(o);
}
}
return result;
} catch (JSONException je) {
return null;
}
}
public static DBObject encode(JSONObject o) {
BasicDBObject result = new BasicDBObject();
try {
Iterator i = o.keys();
while (i.hasNext()) {
String k = (String)i.next();
Object v = o.get(k);
if (v instanceof JSONArray) {
result.put(k, encode((JSONArray)v));
} else if (v instanceof JSONObject) {
result.put(k, encode((JSONObject)v));
} else {
result.put(k, v);
}
}
return result;
} catch (JSONException je) {
return null;
}
}
}
0
我不知道java mongo驱动程序,但在c# mongo driver有BsonSerializer类。 您可以使用它像下面的代码:
var q = BsonSerializer.Deserialize<MyDocument>("{ jsonValueName:jsonValue }");
PLZ检查mongo-java-driver,我感谢它应该包含相同的设施
28
com.mongodb.util.JSON有JSON字符串解析成DBOBJECT的方法。 默认的JSONCallback将根据输入字符串返回一个BasicDBObject或BasicDBList。
Object jsonObj = ...; //any of your org.json objects
Object o = com.mongodb.util.JSON.parse(jsonObj.toString());
DBObject dbObj = (DBObject) o;
0
这个工作,并引发了一个问题,为什么Mongo人决定有一个对象返回类型而不是DBObject:有谁知道吗?
一个很好的选择是,如果你的应用程序中有很多JSON,将使用Jackson作为(反)序列化。
相关问题
- 1. 为什么在MongoDB中使用JSON?
- 2. 在MongoDB中存储JSON
- 3. Rails:在MongoDB中存储JSON
- 4. 在MongoDB中使用Scala - java.lang.NoClassDefFoundError:com/mongodb/DBObject
- 5. 在Django中使用MongoDB runCommand MongoDb引擎
- 6. 如何在mongoDB中使用json输入多个表数据
- 7. 在Python中使用JSON向MongoDB发送查询
- 8. 将JSON转换为实体并使用morphia存储在mongoDB中
- 9. 如何在JSON数据中使用mongoDB的聚合操作
- 10. 在Node.js + MongoDB中使用rest api插入和查询JSON数据
- 11. 如何使用JSON在MongoDB中进行查询?
- 12. 使用sparksql在MongoDB中加载JSON数据
- 13. 避免使用Java和JSON对象在mongoDB中重复输入
- 14. C#MongoDb查询和使用基础JSON
- 15. 使用JSON/Heroku/MongoDB的简单Webservice
- 16. 使用JSON对象更新mongodb文档
- 17. 使用JSON更新MongoDB文档
- 18. 在mongodb中字符串化的json vs json对象内存使用情况
- 19. 使用MongoDB中
- 20. 在MongoDB中使用IF/ELSE
- 21. findOne在mapreduce中使用mongodb
- 22. 在mongodb中使用聚合
- 23. 在mongodb中使用$ gt
- 24. Node.js:在MongoDb中使用Promise
- 25. 在MongoDB中使用流星
- 26. 在MongoDB中使用rails_admin
- 27. 在MongoDB中使用关系
- 28. 无法在MongoDB中导入json
- 29. 在MongoDB中导入JSON或CSV文件
- 30. 错误在MongoDB中JSON格式
是的,我可以序列化为一个字符串并反序列化字符串,但我试图互操作本地对象。不过谢谢。 – Simon 2011-05-04 00:53:41