AI编程助手
AI免费问答

如何在Java中将JSON数组转换为CSV?

WBOY   2023-08-21 20:27   1888浏览 转载

如何在java中将json数组转换为csv?

JSON可以用作数据交换格式,它是轻量级的与语言无关。一个JSONArray可以解析文本字符串以生成类似于向量的对象,并支持java.util.List接口。我们可以使用org.json.CDL类将JSON数组转换为CSV格式,它提供了一个静态方法toString(),用于将JSONArray转换为逗号分隔的文本。我们需要导入org.apache.commons.io.FileUtils包,以使用writeStringToFile()方法将数据存储在CSV文件中。

语法

public static java.lang.String toString(JSONArray ja) throws JSONException

In the below example, we can convert a JSON Array to CSV format.

Example

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

Java免费学习笔记:立即学习
解锁 Java 大师之旅:从入门到精通的终极指南

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除