尝试将 JSON 文件或字符串转换为 CSV 文件会得到一个空的 CSV 文件

Trying to convert a JSON file or string to a CSV file gives an empty CSV file

所以我正在尝试将 JSON 文件(我使用 Google 工作表 API 导出为 JSON)转换为 CSV 文件,即使有是一个正确放置在该位置的 JSON 文件,或者尝试使用字符串代替,它要么显示空指针异常,要么 returns 一个空的 CSV 文件。

示例 JSON 文件:

{
  "range": "products!A1:E4",
  "majorDimension": "ROWS",
  "values": [
    [
      "product_name",
      "price"
    ],
    [
      "Rugrats - Bedtime Bash [VHS]",
      "36.95"
    ],
    [
      "Teenage Mutant Ninja Turtles II - The Secret of the Ooze [VHS]",
      "29.89"
    ],
    [
      "Teenage Mutant Ninja Turtles II - The Secret of the Ooze [VHS]",
      "29.89"
    ]
  ]
}

我在这里尝试使用的示例代码将它们转换为 CSV,

JSONObject output = new JSONObject(<String or file location that holds JSON file>);
File finalFile=new File(<Destination file path>);
JSONArray docs = output.getJSONArray("values");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(finalFile, csv);

我是否在代码中犯了任何错误,或者我应该用不同的 Java 代码来处理这个 JSON 吗?

为什么不直接从表格中写入 API 响应(此示例摘自 Java Sheet API quick-start

public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    final String spreadsheetId = "<SHEET_ID>";
    final String range = "<SHEET_RANGE>";
    Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();
    ValueRange response = service.spreadsheets().values()
            .get(spreadsheetId, range)
            .execute();
    List<List<Object>> values = response.getValues();
    if (values == null || values.isEmpty()) {
        System.out.println("No data found.");
    } else {
        /* Create a new writer */
        PrintWriter writer = new PrintWriter("data.csv");
        for (List<Object> list : values) {
            /* Building the string */
            StringBuilder str = new StringBuilder();
            str.append(list.get(0).toString() + ",");
            str.append(list.get(1).toString() + "\n");
            writer.write(str.toString());
        }
        /* Closing the writer */
        writer.close();
    }
}

无论如何,如果您正确读取 JSON 对象,则机制将完全相同。

已更新

如果你想直接从 JSON 读取你可以使用这个例子(使用 GSON):

public class SheetResponse {
    private String range;
    private String majorDimensions; 
    private List<List<Object>> values;
}

public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    var gson = new Gson();
    var reader = new JsonReader(new FileReader("test.json"));
    SheetResponse sR = gson.fromJson(reader, SheetResponse.class);
    PrintWriter writer = new PrintWriter("data.csv");
    for (List<Object> list : sR.values) {
        /* Building the string */
        StringBuilder str = new StringBuilder();
        str.append(list.get(0).toString() + ",");
        str.append(list.get(1).toString() + "\n");
        writer.write(str.toString());
    }
    /* Closing the writer */
    writer.close();
}
针对一般情况进行了更新
public static void main(String... args) throws IOException, GeneralSecurityException {
    // Build a new authorized API client service.
    var gson = new Gson();
    var reader = new JsonReader(new FileReader("test.json"));
    SheetResponse sR = gson.fromJson(reader, SheetResponse.class);
    PrintWriter writer = new PrintWriter("data.csv");

    for (int i = 0; i < sR.values.size(); i++) {
        var valueRow = sR.values.get(i);
        StringBuilder str = new StringBuilder();
        for (int j = 0; j < valueRow.size(); j++) {
            if (j == valueRow.size() - 1) {
                str.append(valueRow.get(j).toString() + "\n");
            } else {
                str.append(valueRow.get(j).toString() + ",");
            }
        }
        writer.write(str.toString());
    }
    /* Closing the writer */
    writer.close();
}
文档