因此,我嘗試將 JSON 檔案(我已使用 Google Sheets API 匯出為 JSON)轉換為 CSV 檔案,即使在該位置正確放置了一個 JSON 檔案,或者嘗試使用字串,它也顯示為 null指標例外或回傳一個空的 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?
uj5u.com熱心網友回復:
為什么不直接從 Sheets 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();
}
檔案
PrintWriterStringBuilder
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/475898.html
