使用 java 将 JSON 转换为 CSV
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23471634/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert the JSON to CSV using java
提问by Thyagu
I'm trying to convert the JSON to CSV file. But I'm facing the issue in the
JSONArray docs = output.getJSONArray("Text will vary from each execution.");
How to take the value of the getJSONArray(" xxx ") ???
我正在尝试将 JSON 转换为 CSV 文件。但是我在
JSONArray docs = output.getJSONArray("Text will be different from each execution."); 中遇到了这个问题。如何获取 getJSONArray(" xxx ") 的值???
JSONObject output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray("elements");
File file=new File(csvFilepath);
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
Thanks in Advance
提前致谢
回答by Hirak
Something like this?
像这样的东西?
public static void main(String[] args) throws JSONException {
String numbers = "{\"test\":[{\"elements\" : \"1\"},{\"elements\":\"2\"},{\"elements\":\"3\"}]}";
JSONObject output = new JSONObject(numbers);
JSONArray docs = output.getJSONArray("test");
for (int i = 0; i < docs.length(); i++) {
System.out.println(docs.get(i));
}
}
回答by jwenting
That would depend on the structure of your JSON, and the expected layout of the CSV.
There's no cut and paste answer to that, you're going to have to put in some actual effort to map things the way you need them to be mapped.
Select the objects you need from the JSON, then walk through the resulting array and map each to a row in your CSV.
Nothing too strenuous, just plain old loop iteration and file handling.
这取决于 JSON 的结构以及 CSV 的预期布局。
对此没有剪切和粘贴的答案,您将不得不付出一些实际努力来按照您需要的方式映射事物。
从 JSON 中选择您需要的对象,然后遍历结果数组并将每个对象映射到 CSV 中的一行。
没什么太费劲的,只是简单的旧循环迭代和文件处理。
回答by Thyagu
I got the output with the below code
我得到了以下代码的输出
String[] Names=output.getNames(output);
JSONArray docs =output.getJSONArray(Names[0]);
回答by skap
If you are trying to convert JSON document to CSV then you can try the library json2flat.
如果您尝试将 JSON 文档转换为 CSV,那么您可以尝试使用json2flat库。
It takes any dynamic JSON document and tries to convert it into a suitable format.
它接受任何动态 JSON 文档并尝试将其转换为合适的格式。
For code usage and sample JSON conversion please click on this link.
有关代码使用和示例 JSON 转换,请单击此链接。