Java:将json数组插入MongoDB时出错

问题描述 投票:1回答:1

我正在努力将CSV文件插入MongoDB。首先,我将我的CSV转换为Json格式的数组(参考:https://dzone.com/articles/how-to-convert-csv-to-json-in-java),然后尝试将其上传到MongoDB,但面临以下错误(readStartDocument只能在CurrentBSONType为DOCUMENT时调用,而不是在CurrentBSONType为ARRAY时调用。):

Exception in thread "main" org.bson.BsonInvalidOperationException: readStartDocument can only be called when CurrentBSONType is DOCUMENT, not when CurrentBSONType is ARRAY.
    at org.bson.AbstractBsonReader.verifyBSONType(AbstractBsonReader.java:692)
    at org.bson.AbstractBsonReader.checkPreconditions(AbstractBsonReader.java:724)
    at org.bson.AbstractBsonReader.readStartDocument(AbstractBsonReader.java:452)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:148)
    at org.bson.codecs.DocumentCodec.decode(DocumentCodec.java:45)
    at org.bson.Document.parse(Document.java:105)
    at org.bson.Document.parse(Document.java:90)
    at com.ucm.json.ConnectMongoDB.connectToMongoDB(ConnectMongoDB.java:52)
    at com.ucm.json.Main.main(Main.java:15)

我的JSON字符串(结果)如下所示:

[ {
  "query" : "ecn",
  "type" : "KeywordMatch",
  "url" : "http://insidedell.com/ecn",
  "description" : "ECN"
}, {
  "query" : "product marketing",
  "type" : "PhraseMatch",
  "url" : "http://dellemc.com/product",
  "description" : "Products"
}, {
  "query" : "jive",
  "type" : "ExactMatch",
  "url" : "http://test.com/jive",
  "description" : "Jive test"
} ]

下面是我的代码:第1步:将CSV转换为JSON格式的字符串数组

public class CreateJSON {

    public String query;
    public String type;
    public String url;
    public String description; 
    String result ;
    public CreateJSON() {

    }
    public CreateJSON(String query,String type,String url,String description) {
        this.query = query;
        this.type = type;
        this.url = url;
        this.description = description;

    }

    public String createJsonFromCSV() throws IOException{
        String csvFile = "C:\\Projects\\frontKeymatch_default_frontend.csv";

        List<CreateJSON> createObjects = null;
        Pattern pattern = Pattern.compile(",");
        try (BufferedReader in = new BufferedReader(new FileReader(csvFile));){

            createObjects = in.lines().map(line ->{
                String[] x = pattern.split(line);
                return new CreateJSON(x[0],x[1],x[2],x[3]);

            }).collect(Collectors.toList());


             ObjectMapper mapper = new ObjectMapper();
             mapper.enable(SerializationFeature.INDENT_OUTPUT);
             result =  mapper.writeValueAsString(createObjects);

        } 
         return result;

    }
}

步骤2)连接到MongoDB并插入数据

public class ConnectMongoDB{
    public void connectToMongoDB(String resultFromCSV) throws JsonGenerationException, JsonMappingException, IOException {

    MongoClient mongo = new MongoClient( "localhost" ,27017);
    Document doc = Document.parse(resultFromCSV);

            mongo.getDatabase("db").getCollection("collection").insertOne(doc);

            System.out.println("success");

        }
   }    

第3步:我的主要方法:

public class Main {

    public static void main(String[] args) throws FileNotFoundException, IOException {

        CreateJSON upload = new CreateJSON();
        ConnectMongoDB mongo = new ConnectMongoDB();
        mongo.connectToMongoDB(upload.createJsonFromCSV());
    }

}

任何帮助表示赞赏。谢谢

java json mongodb csv
1个回答
1
投票

没有从json数组直接转换为Document。 Document.parse适用于单个文档,是出错的原因。

您可以更新方法以删除中间CreateJSON对象和ObjectMapper,并直接将csv行映射到Document并将它们收集为List。

将下面的方法作为静态方法移动到主类,并使用InsertMany插入所有文档。

主要方法。

public class Main {

public static void main(String[] args) throws FileNotFoundException, IOException {
    ConnectMongoDB mongo = new ConnectMongoDB();
    mongo.connectToMongoDB(createJsonFromCSV());
}

public static List<Document> createJsonFromCSV() throws IOException {
    String csvFile = "C:\\Projects\\frontKeymatch_default_frontend.csv";
    List<Document> createObjects = null;
    Pattern pattern = Pattern.compile(",");
    try (BufferedReader in = new BufferedReader(new FileReader(csvFile));){
          createObjects = in.lines().map(line ->{
             String[] x = pattern.split(line);
             return new Document("query",x[0]).append("type", x[1]) //append other fields
          }).collect(Collectors.toList());
       }
     return createObjects;
    }
}

public class ConnectMongoDB{
    public void connectToMongoDB(List<Document> docs) throws IOException {
    MongoClient mongo = new MongoClient( "localhost" ,27017);
    mongo.getDatabase("db").getCollection("collection").insertMany(docs);
    System.out.println("success");
   }
}   
© www.soinside.com 2019 - 2024. All rights reserved.