如何在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 红包祝福语简短10字
18 周六早晨祝福语简短