如何在Java中将JSON数组转换为CSV?
JSON可以用作数据交换格式, 并且是轻量级 且与 语言无关的。甲JSONArray 可以从一个字符串解析文本以产生向量样物体和支承件 的java.util。列表接口。我们可以使用org.json.CDL类将JSONArray转换为CSV格式 ,它可以提供静态方法toString(), 以将JSONArray转换为以逗号分隔的文本。我们需要导入org.apache.commons.io.FileUtils包,以使用writeStringToFile() 方法将数据存储在CSV文件中。
语法
public static java.lang.String toString(JSONArray ja) throws JSONException
在下面的示例中,我们可以将JSON数组转换为CSV格式。
示例
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.json.*;
public class ConvertJsonToCSVTest {
public static void main(String[] args) throws JSONException {
String jsonArrayString = "{\"fileName\": [{\"first name\": \"Ravi\",\"last name\": \"Chandra\",\"location\": \"Bangalore\"}]}";
JSONObject output;
try {
output = new JSONObject(jsonArrayString);
JSONArray docs = output.getJSONArray("fileName");
File file = new File("EmpDetails.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
System.out.println("Data has been Sucessfully Writeen to "+ file);
System.out.println(csv);
}
catch(Exception e) {
e.printStackTrace();
}
}
}输出结果
Data has been Sucessfully Writeen to EmpDetails.csv last name,first name,location Chandra,Ravi,Bangalore
热门推荐
10 生日祝福语简短独特格式
11 英语祝福语搞笑短句简短
12 祝福语结婚诗句大全简短
13 喜欢的人送礼祝福语简短
14 高考给舍友祝福语简短
15 广东考试祝福语朋友简短
16 高兴的结婚祝福语简短
17 新婚祝福语简短老同学
18 婚礼美句简短祝福语