import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CsvToJsonConverter {
public static void main(String[] args) {
String csvFilePath = "D:\\Code\\tass.csv"; // 替换为你的CSV文件路径
String jsonFilePath = "D:\\Code\\tass.ndjson"; // 替换为你希望保存的JSON文件路径
convertCsvToJson(csvFilePath, jsonFilePath);
}
public static void convertCsvToJson(String csvFilePath, String jsonFilePath) {
try (
FileReader fileReader = new FileReader(csvFilePath);
CSVParser csvParser = new CSVParser(fileReader, CSVFormat.DEFAULT.withFirstRecordAsHeader());
Writer writer = Files.newBufferedWriter(Paths.get(jsonFilePath))
) {
ObjectMapper objectMapper = new ObjectMapper();
//NDJSON格式设置为false
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
for (CSVRecord csvRecord : csvParser) {
Map<String, String> recordMap = csvRecord.toMap();
//从键中删除任何BOM字符和不必要的引号
Map<String, String> cleanedMap = cleanKeys(recordMap);
//将索引操作和文档写入文件
StringWriter indexActionWriter = new StringWriter();
objectMapper.writeValue(indexActionWriter, Map.of("index", Map.of("_index", "es索引名")));
writer.write(indexActionWriter.toString());
writer.write("\n");
StringWriter documentWriter = new StringWriter();
objectMapper.writeValue(documentWriter, cleanedMap);
writer.write(documentWriter.toString());
writer.write("\n");
}
System.out.println("文件生成成功,路径为: " + jsonFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
private static Map<String, String> cleanKeys(Map<String, String> map) {
Map<String, String> cleanedMap = new HashMap<>();
for (Map.Entry<String, String> entry : map.entrySet()) {
//删除BOM字符并修剪任何前导/尾随空格
String cleanKey = entry.getKey().replace("\uFEFF", "").trim();
//删除键中不必要的引号
cleanKey = cleanKey.replaceAll("^\"|\"$", "");
cleanedMap.put(cleanKey, entry.getValue());
}
return cleanedMap;
}
}
<!--依赖-->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
<version>1.8</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>