现在业务场景是,需要将一段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读取文件代码
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}