在 Java 中将 JSON 转换为 XLS/CSV
问题描述:
有人有将 JSON 文档转换为 XLS/CSV 文件的示例 Java 代码吗?我曾尝试在 Google 上进行搜索,但无济于事.
Does anyone have any sample Java code to convert a JSON document to XLS/CSV file? I have tried to search on Google but to no avail.
答
您只能将 JSON 数组转换为 CSV 文件.
You could only convert a JSON array into a CSV file.
比方说,你有一个像下面这样的 JSON :
Lets say, you have a JSON like the following :
{"infile": [{"field1": 11,"field2": 12,"field3": 13},
{"field1": 21,"field2": 22,"field3": 23},
{"field1": 31,"field2": 32,"field3": 33}]}
让我们看看将其转换为 csv 的代码:
Lets see the code for converting it to csv :
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class JSON2CSV {
public static void main(String myHelpers[]){
String jsonString = "{"infile": [{"field1": 11,"field2": 12,"field3": 13},{"field1": 21,"field2": 22,"field3": 23},{"field1": 31,"field2": 32,"field3": 33}]}";
JSONObject output;
try {
output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray("infile");
File file=new File("/tmp2/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
现在您获得了从 JSON 生成的 CSV.
Now you got the CSV generated from JSON.
它应该是这样的:
field1,field2,field3
11,22,33
21,22,23
31,32,33
maven 依赖就像,
The maven dependency was like,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
2019 年 12 月 13 日更新:
更新答案,因为现在我们也可以支持复杂的 JSON 数组.
Updating the answer, since now we can support complex JSON Arrays as well.
import java.nio.file.Files;
import java.nio.file.Paths;
import com.github.opendevl.JFlat;
public class FlattenJson {
public static void main(String[] args) throws Exception {
String str = new String(Files.readAllBytes(Paths.get("path_to_imput.json")));
JFlat flatMe = new JFlat(str);
//get the 2D representation of JSON document
flatMe.json2Sheet().headerSeparator("_").getJsonAsSheet();
//write the 2D representation in csv format
flatMe.write2csv("path_to_output.csv");
}
}
依赖项和文档详细信息位于 link
dependency and docs details are in link