如何将JSON对象转换为DBObject?

吲哚尼

我有一个要存储到MongoDB中的JSON对象obj:

JSONObject obj = new JSONObject();
obj.put("title", obj1.title);
//For rules:
Map m = new LinkedHashMap();
// for rules, first create JSONArray  
JSONArray ja = new JSONArray(); 

m = new LinkedHashMap();
m.put("right_connective", "&&");
m.put("attribute", "amount");
m.put("operator", "<=");
m.put("value", obj1.amount);
m.put("rank", 1);
m.put("encapsulated", "false");
ja.add(m);

m = new LinkedHashMap();
m.put("left_connective", "&&");
m.put("right_connective", "&&");
m.put("attribute", "project");
m.put("operator", "==");
m.put("value", obj1.project);
m.put("rank", 2);
m.put("encapsulated", "false");
ja.add(m);

m = new LinkedHashMap();
m.put("left_connective", "&&");
m.put("right_connective", "&&");
m.put("attribute", "type");
m.put("operator", "==");
m.put("value", obj1.type);
m.put("rank", 3);
m.put("encapsulated", "false");
ja.add(m);

m = new LinkedHashMap();
m.put("left_connective", "&&");
m.put("attribute", "car");
m.put("operator", "==");
m.put("value", obj1.car);
m.put("rank", 4);
m.put("encapsulated", "false");
ja.add(m);

obj.put("rule", ja);



Document doc = Document.parse( obj.toString() );
BasicDBObject dbObject = mapper.readValue(obj, BasicDBObject.class);
collection.insert(dbObject);

我收到一个错误,指出“映射器无法解析为类型”。我需要包括哪些进口声明?否则,您可以建议其他方法吗?我不想走MongoDocument路线,因为insertOne()函数在写入数据库时​​会跳过一些文档。

Ilopezluna

如果您正在使用,则不需要映射器org.json.JSONObject

 DBObject object = (DBObject) JSON.parse(obj.toString());
 collection.insert(object)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章