简体   繁体   English

如何在不知道 json 文件中的属性的情况下,使用 ZD52387880E75EA281817A72 代码动态上传同一文件夹下的多个 json 文件到 MongoDB

[英]How to upload multiple json files under same folder dynamically without knowing the attributes in the json file to MongoDB using Java code

I am getting error:我收到错误:

exception in thread "main" org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is ARRAY.线程“main”org.bson.BsonInvalidOperationException 中的异常:readStartDocument 只能在 CurrentBSONType 为 DOCUMENT 时调用,而 CurrentBSONType 为 ARRAY 时不能调用。

With the below code I am trying to insert only one json file.使用下面的代码,我试图只插入一个 json 文件。 Could you please help me?请你帮助我好吗?

   public class hallo {

    public static void main( String args[] ) {

        // Creating a Mongo client
        MongoClient mongo = new MongoClient( "localhost" , 27017 );


        // Accessing the database
        MongoDatabase database = mongo.getDatabase("dumpJsonFiles");
        //System.out.println("Credentials ::"+ credential);

        //Creating a collection
        //database.createCollection("sampleCollection1");
        System.out.println("Collection created successfully");
        MongoCollection<Document> collection = database.getCollection("new_name");
        System.out.println("Collection myCollection selected successfully");
        Document document = new Document("title", "MongoDB")
                .append("description", "database")
                .append("likes", 100)
                .append("url", "http://www.tutorialspoint.com/mongodb/")
                .append("by", "tutorials point");

        //Inserting document into the collection
        collection.insertOne(document);
        System.out.println("Document inserted successfully");
        List<InsertOneModel<Document>> docs = new ArrayList<>();
        int count = 0;
        int batch = 100;
        try (BufferedReader br = new BufferedReader(new FileReader("sample.json"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("line is "+line);
                docs.add(new InsertOneModel<>(Document.parse(line)));
                count++;
                if (count == batch) {
                    collection.bulkWrite(docs, new BulkWriteOptions().ordered(false));
                    docs.clear();
                    count = 0;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (count > 0) {
            collection.bulkWrite(docs, new BulkWriteOptions().ordered(false));
        }
        //DBObject dbObject = (DBObject)JSON.parse("sample.json");

        System.out.println("Document inserted 2 successfully");

    }
}

The input JSON file sample contents (copied from comments):输入 JSON 文件示例内容(从注释中复制):

{
   "Details":{
      "Name":"AC",
      "Rollno":"5978",
      "section":"",
      "Maths":"10",
      "Science":"20",
      "social":"20",
      "English":"30"
   }
}

Another json file is:另一个 json 文件是:

[
   {
      "Name":"Table",
      "Description":"Used",
      "Marks":[
         {
            "Social":"10",
            "Science":"20",
            "Maths":"30",
            "English":"40",
            "Hindi":"50",
            "Computers":[
               {
                  "Lab":"10",
                  "Theory":"20"
               }
            ]
         }
      ]
   }
]

I am getting error:我收到错误:

exception in thread "main" org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is ARRAY.线程“main”org.bson.BsonInvalidOperationException 中的异常:readStartDocument 只能在 CurrentBSONType 为 DOCUMENT 时调用,而 CurrentBSONType 为 ARRAY 时不能调用。

With the below code I am trying to insert only one json file.使用下面的代码,我试图只插入一个 json 文件。 Could you please help me?请你帮助我好吗?

   public class hallo {

    public static void main( String args[] ) {

        // Creating a Mongo client
        MongoClient mongo = new MongoClient( "localhost" , 27017 );


        // Accessing the database
        MongoDatabase database = mongo.getDatabase("dumpJsonFiles");
        //System.out.println("Credentials ::"+ credential);

        //Creating a collection
        //database.createCollection("sampleCollection1");
        System.out.println("Collection created successfully");
        MongoCollection<Document> collection = database.getCollection("new_name");
        System.out.println("Collection myCollection selected successfully");
        Document document = new Document("title", "MongoDB")
                .append("description", "database")
                .append("likes", 100)
                .append("url", "http://www.tutorialspoint.com/mongodb/")
                .append("by", "tutorials point");

        //Inserting document into the collection
        collection.insertOne(document);
        System.out.println("Document inserted successfully");
        List<InsertOneModel<Document>> docs = new ArrayList<>();
        int count = 0;
        int batch = 100;
        try (BufferedReader br = new BufferedReader(new FileReader("sample.json"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println("line is "+line);
                docs.add(new InsertOneModel<>(Document.parse(line)));
                count++;
                if (count == batch) {
                    collection.bulkWrite(docs, new BulkWriteOptions().ordered(false));
                    docs.clear();
                    count = 0;
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (count > 0) {
            collection.bulkWrite(docs, new BulkWriteOptions().ordered(false));
        }
        //DBObject dbObject = (DBObject)JSON.parse("sample.json");

        System.out.println("Document inserted 2 successfully");

    }
}

The input JSON file sample contents (copied from comments):输入 JSON 文件示例内容(从注释中复制):

{
   "Details":{
      "Name":"AC",
      "Rollno":"5978",
      "section":"",
      "Maths":"10",
      "Science":"20",
      "social":"20",
      "English":"30"
   }
}

Another json file is:另一个 json 文件是:

[
   {
      "Name":"Table",
      "Description":"Used",
      "Marks":[
         {
            "Social":"10",
            "Science":"20",
            "Maths":"30",
            "English":"40",
            "Hindi":"50",
            "Computers":[
               {
                  "Lab":"10",
                  "Theory":"20"
               }
            ]
         }
      ]
   }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Java在mongodb中上传json文件? - How to upload a json file in mongodb using Java? java - 如何在不知道java.nio.file的文件名的情况下检查文件夹大小或包含Java中的文件? - How to check folder size or containing files in Java without knowing the file name with java.nio.file? 如何在不知道键的情况下动态地将嵌套的 Json 对象/数组转换为基于键的多个列表 - How to converting a nested Json object/array to multiple lists based on keys Dynamically without knowing the keys 在不知道 JSON 格式的情况下用 Java 解析 JSON - Parsing JSON in Java without knowing JSON format 无法使用 Java 在 MongoDB 中上传 JSON - Not able to upload JSON in MongoDB using Java 如何使用Java读取多个JSON文件并将其写入单个JSON文件 - How to read multiple JSON files and write it to a single JSON file using java 如何使用普通Java代码读取JSON字符串(不使用任何Jar文件) - How to Read JSON String using plain Java Code (without using any Jar files) 如何使用Dropbox Java API同时上传多个文件 - How to upload multiple files at the same time using the dropbox java api 如何使用Java在单个JSON文件中读取多个JSON文档? - How to read multiple JSON docs in single JSON file using Java? 在不知道属性名称和属性数量的情况下处理json对象 - Handles json objects without knowing the attribute name and number of attributes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM