Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

แปลง JSON Array เป็น CSV ใน Java ด้วย org.json.CDL

JSON เป็น Data-Interchange Format แบบ Lightweight Language-Independent JSONArray Parse String เป็น Vector-like Object รองรับ java.util.List Interface แปลง JSON Array เป็น CSV Format ด้วยคลาส org.json.CDL มี Static Method toString() แปลง JSONArray เป็น Comma-Delimited Text ใช้ org.apache.commons.io.FileUtils เขียนไฟล์ CSV ด้วย writeStringToFile()

Syntax

public static String toString(JSONArray ja) throws JSONException

ตัวอย่าง: Convert JSON Array to 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 Successfully Written to " + file);
            System.out.println(csv);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

ผลลัพธ์

Data has been Successfully Written to EmpDetails.csv
last name,first name,location
Chandra,Ravi,Bangalore

สังเกต: CSV Header มาจาก JSON Keys (เรียงตาม Alphabetical Order ของ Keys) ใช้ CDL.toString(JSONArray) แปลง Array ของ Objects เป็น CSV Rows

Dependencies:

  • org.json:json
  • commons-io:commons-io