如何在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 婚前女儿生日祝福语简短