Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chuyển JSONArray sang CSV trong Java (org.json.CDL)

JSON dùng làm data-interchange format nhẹ, language independent. JSONArray parse String tạo object giống vector, hỗ trợ interface java.util.List. Chuyển JSON Array sang CSV format dùng org.json.CDL class, cung cấp static method toString() chuyển JSONArray thành comma-delimited text. Cần import org.apache.commons.io.FileUtils để lưu ra file CSV dùng writeStringToFile().

Cú pháp

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

Ví dụ minh họa

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("Đã ghi dữ liệu thành công vào " + file);
            System.out.println(csv);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Kết quả

Đã ghi dữ liệu thành công vào EmpDetails.csv
last name,first name,location
Chandra,Ravi,Bangalore

Lưu ý: CDL.toString() dùng key của object đầu tiên làm header CSV (theo thứ tự alphabet). Các object sau phải có cùng cấu trúc key. Thư viện org.json và commons-io cần thêm dependency. Để tùy biến header/order, cần tự implement hoặc dùng thư viện CSV chuyên dụng (OpenCSV, Apache Commons CSV).