JAVA实现CSV文件转JSON。
CSV文件一般是以逗号为分隔值的文件(Comma-Separated Values,CSV,有时也称为字符分隔值,因为分隔字符也可以不是逗号),其文件以纯文本形式存储表格数据(数字和文本)。

JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。示例如下
{
"name": "John Doe",
"age": 18,
"address":
{
"country" : "china",
"zip-code": "10000"
}
}
JAVA实现CSV转JSON的思路是根据CSV格式特点使用 逗号进行切割,然后使用String对象将分割的对象进行拼接成JSON格式。
import java.io.*;
import java.util.Arrays;
import java.util.List;
public class CsvToJson {
private List<String> stringToList(String s, String sep) {
if (s == null) {
return null;
}
String[] parts = s.split(sep);
return Arrays.asList(parts);
}
private String stringToJson(List<String> header, List<String> lineData) throws Exception {
if (header == null || lineData == null) {
throw new Exception("输入不能为null。");
}
else if (header.size() != lineData.size()) {
throw new Exception("表头个数和数据列个数不等。");
}
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("{ ");
for (int i = 0; i < header.size(); i++) {
String mString = String.format("\"%s\": \"%s\"", header.get(i), lineData.get(i));
sBuilder.append(mString);
if (i != header.size() - 1) {
sBuilder.append(", ");
}
}
sBuilder.append(" }");
return sBuilder.toString();
}
public void ConvertToJson(InputStream filePath, OutputStream outPutPath) throws Exception {
InputStreamReader isr = new InputStreamReader(filePath,"utf-8");
BufferedReader reader = new BufferedReader(isr);
OutputStreamWriter osw = new OutputStreamWriter(outPutPath,"utf-8");
BufferedWriter writer = new BufferedWriter(osw);
try {
String sep = ",";
String headerStr = reader.readLine();
if (headerStr.trim().isEmpty()) {
System.out.println("表格头不能为空");
return;
}
List<String> header = stringToList(headerStr, sep);
String line;
int lineCnt = 1;
while ((line = reader.readLine()) != null) {
if (line.trim().isEmpty()) {
System.out.println("第" + lineCnt + "行为空,已跳过");
continue;
}
List<String> lineData = stringToList(line, sep);
if (lineData.size() != header.size()) {
String mString = String.format("第%d行数据列和表头列个数不一致\r\n%s", lineCnt, line);
System.err.println(mString);
break;
}
String jsonStr = stringToJson(header, lineData);
writer.write(jsonStr);
writer.write("\r\n");
lineCnt++;
}
} finally {
if (reader != null) {
reader.close();
}
if (writer != null) {
writer.close();
}
}
}
public static void main(String[] args) throws Exception {
InputStream filePath = new FileInputStream("/Users/Desktop/dwa/11111.csv");
OutputStream outPutPath = new FileOutputStream("/Users/Desktop/2222.json");
CsvToJson csvToJSon = new CsvToJson();
csvToJSon.ConvertToJson(filePath, outPutPath);
System.out.println("转换完成");
}
}