使用Java将JSONArray转换为CSV可以通过以下步骤实现:
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.json.JSONArray;
import org.json.JSONObject;
public void convertJSONArrayToCSV(JSONArray jsonArray, String outputPath) {
try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(outputPath), CSVFormat.DEFAULT)) {
// 添加表头
JSONObject firstObject = jsonArray.getJSONObject(0);
firstObject.keySet().forEach(key -> {
try {
csvPrinter.print(key);
} catch (IOException e) {
e.printStackTrace();
}
});
csvPrinter.println();
// 添加数据
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
jsonObject.keySet().forEach(key -> {
try {
csvPrinter.print(jsonObject.get(key));
} catch (IOException e) {
e.printStackTrace();
}
});
csvPrinter.println();
}
csvPrinter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
JSONArray jsonArray = new JSONArray("[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30}]");
String outputPath = "output.csv";
convertJSONArrayToCSV(jsonArray, outputPath);
}
这样,JSONArray中的数据就会被转换为CSV格式,并保存到指定的输出文件中。
优势:
应用场景:
腾讯云相关产品推荐:
领取专属 10元无门槛券
手把手带您无忧上云