JSON สามารถใช้เป็น รูปแบบการแลกเปลี่ยนข้อมูล และ น้ำหนักเบา และไม่ขึ้นกับภาษา . JSONArray สามารถแยกวิเคราะห์ข้อความจากสตริงเพื่อสร้าง เวกเตอร์ -like วัตถุและรองรับ java.util. รายการ อินเตอร์เฟซ. เราสามารถแปลง JSON Array เป็น รูปแบบ CSV โดยใช้ org.json.CDL class มันสามารถจัดเตรียมวิธีการแบบคงที่ toString(), เพื่อ แปลง JSONArray เป็นข้อความที่คั่นด้วยจุลภาค . เราจำเป็นต้องนำเข้า org.apache.commons.io.FileUtils แพ็คเกจเพื่อเก็บข้อมูลในไฟล์ CSV โดยใช้ writeStringToFile() วิธีการ
ไวยากรณ์
public static java.lang.String toString(JSONArray ja) throws JSONException
ในตัวอย่างด้านล่าง เราสามารถแปลง JSON Array เป็นรูปแบบ 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