本文介绍了在Java中将JSON转换为XLS / CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人有任何示例Java代码将JSON文档转换为XLS / CSV文件吗?我尝试在Google上搜索,但没有效果。
解决方案
只能将JSON数组转换为CSV文件。 / p>
假设你有一个类似下面的JSON:
infile:[{field1:11,field2:12,field3:13},
{field1:21,field2:22,field3:23} b $ b {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输出;
try {
output = new JSONObject(jsonString);
JSONArray docs = output.getJSONArray(infile);
文件file = new File(/ tmp2 / fromJSON.csv);
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file,csv);
} catch(JSONException e){
e.printStackTrace();
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
}
}
它应该看起来像这样:
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>
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.
解决方案
You could only convert a JSON array into a CSV file.
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}]}
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();
}
}
}
Now you got the CSV generated from JSON.
It should look like this:
field1,field2,field3
11,22,33
21,22,23
31,32,33
The maven dependency was like,
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20090211</version>
</dependency>
这篇关于在Java中将JSON转换为XLS / CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!