将CSV文件转换为JSON格式,以便将其保存在MongoDB中,可以通过以下步骤实现:
以下是一个示例代码,演示了如何将CSV文件转换为JSON格式并保存到MongoDB中(使用Spring框架、Jackson库和MongoDB的Java驱动程序):
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import import com.fasterxml.jackson.databind.ObjectMapper;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.util.JSON;
// 定义Spring控制器
@RestController
public class CSVtoJSONController {
@PostMapping("/convert")
public String convertCSVtoJSON(@RequestParam("csvFile") MultipartFile csvFile) {
try {
// 读取CSV文件并转换为Java对象
List<YourObject> objects = readCSV(csvFile);
// 将Java对象转换为JSON字符串
String json = convertToJSON(objects);
// 连接到MongoDB数据库
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase database = mongoClient.getDatabase("yourDatabase");
MongoCollection collection = database.getCollection("yourCollection");
// 将JSON字符串转换为MongoDB的BSON对象并插入到集合中
collection.insert((DBObject) JSON.parse(json));
// 关闭MongoDB连接
mongoClient.close();
return "CSV to JSON conversion and MongoDB insertion successful!";
} catch (Exception e) {
e.printStackTrace();
return "Error occurred during CSV to JSON conversion and MongoDB insertion.";
}
}
private List<YourObject> readCSV(MultipartFile csvFile) throws IOException {
List<YourObject> objects = new ArrayList<>();
CSVReader csvReader = new CSVReader(new InputStreamReader(csvFile.getInputStream()));
String[] line;
while ((line = csvReader.readNext()) != null) {
YourObject object = new YourObject();
object.setField1(line[0]);
object.setField2(line[1]);
// 设置其他字段...
objects.add(object);
}
csvReader.close();
return objects;
}
private String convertToJSON(List<YourObject> objects) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(objects);
}
}
请注意,上述示例代码仅为演示目的,实际应用中可能需要根据具体需求进行适当修改和优化。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云