有没有人有将JSON文档转换为XLS / CSV文件的Java示例代码?我已经尝试在Google上搜索,但没有结果。
有没有样例Java代码可以将JSON文档转化为XLS/CSV文件呢?我已经在Google上进行了搜索,但是没有找到相关的信息。你只能将JSON数组转换为CSV文件。
假设你有以下的JSON:
{"infile": [{"field1": 11,"field2": 12,"field3": 13},
{"field1": 21,"field2": 22,"field3": 23},
{"field1": 31,"field2": 32,"field3": 33}]}
让我们看一下将其转换为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文件。
它应该是这样的:field1,field2,field3
11,22,33
21,22,23
31,32,33
这个 Maven 依赖项的样子就像这样:
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
更新于2019年12月13日:
现在我们也支持复杂的JSON数组。
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");
}
}
依赖项和文档细节在链接中。
FileUtils.writeStringToFile(file, csv, null);
第三个参数是编码,null表示平台默认。 - Sridhar{'foo': {'bar': [1, 2, 3]}}
映射到电子表格中? - user647772JSON文档基本上由列表和字典组成。没有明显的方法将这样的数据结构映射到二维表中。