如何使用java将json对象转换为mongodb中的Document

时间:2016-08-16 08:56:42

标签: java json mongodb

我使用下面的示例json:

JSONObject json=new JSONObject();
            json.put("time_range", "22-23");
            json.put("flow_id", "786");

尝试按如下方式转换为Document:

Document doc = (Document) JSON.parse(jsonlist.toString()); // conversion from json to Document

col.insertOne(doc); // inserting into Mongo collection

我面临以下错误:

 java.lang.ClassCastException: com.mongodb.BasicDBObject cannot be cast to org.bson.Document    

任何人都可以帮我解决这个问题...

2 个答案:

答案 0 :(得分:15)

试试这个

Document doc = Document.parse( jsonlist.toString() );

答案 1 :(得分:1)

您可以尝试使用以下示例代码在mongo中插入数据: -

{{1}}

对于您的情况,您可以对您的JSON对象进行Stringify,然后尝试将其插入mongodb ..