【问题标题】:How to convert json Object to Document in mongodb using java [duplicate]如何使用java将json对象转换为mongodb中的文档[重复]
【发布时间】:2016-12-22 13:45:10
【问题描述】:

我正在使用以下示例 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    

谁能帮我解决这个问题...

【问题讨论】:

    标签: java json mongodb


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

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

      String json = "{ 'name' : 'lokesh' , " +
                      "'website' : 'howtodoinjava.com' , " +
                      "'address' : { 'addressLine1' : 'Some address' , " +
                                    "'addressLine2' : 'Karol Bagh' , " +
                                    "'addressLine3' : 'New Delhi, India'}" +
                                  "}";
      
      DBObject dbObject = (DBObject)JSON.parse(json);
      
      collection.insert(dbObject);
      

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

      【讨论】:

      • 题目要求将JSONObject转为Document
      猜你喜欢
      • 2016-11-03
      • 1970-01-01
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 2011-09-22
      • 1970-01-01
      • 1970-01-01
      • 2017-01-03
      相关资源
      最近更新 更多