Java,如何读取json文件,并将其存入Mongodb数据库中

现在业务场景是,需要将一段json数据,要求用java的方式,导入到mongo数据库中,请教下,代码思路是什么,有没有demo

如有帮助,请采纳。

参考如下:

import com.mongodb.MongoClient;
import com.mongodb.DBObject;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;


// 构造一个Json字符串
String json = " {" +
                " 'school_code' : '111111', " +
                " 'school_name' : '汉东政法大学', " +
                " 'teacher_idcard' : '0000001', " +
                " 'teacher_name' : '高育良' " +
                " } ";

MongoClient mongoClient = new MongoClient("10.4.120.83", 27017);

MongoDatabase database = mongoClient.getDatabase("dbName");

MongoCollection<DBObject> collection = database.getCollection("collectionName", DBObject.class);    

DBObject bson = (DBObject)JSON.parse(json);

collection.insertOne(bson);

java对json解析 有fastjson gson或者 jackson包

mongodb一般都是js写的增删改查。

可以用mongodb driver;

 

如果是pc端,将json数据存入文件,java读取文件内容, 使用FASTjson转为java对象,导入到mongoDB

 

如果是web端,写一个文本域,接口读取到文本域的值,使用FASTjson转为java对象,导入到mongoDB

java读取文件代码

  1. /**

  2. * 以行为单位读取文件,常用于读面向行的格式化文件

  3. */

  4. public static void readFileByLines(String fileName) {

  5. File file = new File(fileName);

  6. BufferedReader reader = null;

  7. try {

  8. System.out.println("以行为单位读取文件内容,一次读一整行:");

  9. reader = new BufferedReader(new FileReader(file));

  10. String tempString = null;

  11. int line = 1;

  12. // 一次读入一行,直到读入null为文件结束

  13. while ((tempString = reader.readLine()) != null) {

  14. // 显示行号

  15. System.out.println("line " + line + ": " + tempString);

  16. line++;

  17. }

  18. reader.close();

  19. } catch (IOException e) {

  20. e.printStackTrace();

  21. } finally {

  22. if (reader != null) {

  23. try {

  24. reader.close();

  25. } catch (IOException e1) {

  26. }

  27. }

  28. }

  29.