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

来自:互联网
时间:2023-08-21
阅读:

语法

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中将JSON数组转换为CSV

返回顶部
顶部