[英]A converter from JSON to CSV in Java doesn't work properly
我正在做一個從 json 到 csv 文件的轉換器。 我已經嘗試過此鏈接中的解決方案,但無法正常工作: Converting JSON to XLS/CSV in Java
問題是我沒有單獨列中的數據,而且我還有不同順序的列名。 有沒有可能解決這個問題?
我的 json 看起來像這樣:
{
"Code":2,
"Description":"OK",
"Status":0,
"Items":[{ "City":"nameOfCity",
"Country":"nameOfCountry",
"CountryCode":"US",
"Latitude":"11.11111",
"Longitude":"-11.11111",
"Name":"name of Company",
"Region":"nameofRegion",
"ServisID":"111AAA111AA",
"SiteAddress":"number and street 2301",
"ZipCode":"1111"},
{"City":"nameOfCity2",
"Country":"nameOfCountry",
"CountryCode":"US",
"Latitude":"22.22222",
"Longitude":"22.2222222222",
"Name":"name of Company2",
"Region":"nameofRegion",
"ServisID":"111BBB111BB",
"SiteAddress":null,
"ZipCode":null}
, ...etc.
我的代碼:
String bodyStr = new String(proxyResponse.getBody());
JSONObject output;
try {
output = new JSONObject(bodyStr);
JSONArray docs = output.getJSONArray("Items");
File file = new File("C:/folder/fromJSON.csv");
String csv = CDL.toString(docs);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
結果(第一個預期):
使用以下代碼按預期工作。 我看不出你的代碼和我的代碼有什么大的區別......
public static void main(String[] args) throws IOException {
String inputJson = "{\"Code\":2,\"Description\":\"OK\",\"Status\":0,\"Items\":[{\"City\":\"nameOfCity\",\"Country\":\"nameOfCountry\",\"CountryCode\":\"US\",\"Latitude\":\"11.11111\",\"Longitude\":\"-11.11111\",\"Name\":\"name of Company\",\"Region\":\"nameofRegion\",\"ServisID\":\"111AAA111AA\",\"SiteAddress\":\"number and street 2301\",\"ZipCode\":\"1111\"},{\"City\":\"nameOfCity2\",\"Country\":\"nameOfCountry\",\"CountryCode\":\"US\",\"Latitude\":\"22.22222\",\"Longitude\":\"22.2222222222\",\"Name\":\"name of Company2\",\"Region\":\"nameofRegion\",\"ServisID\":\"111BBB111BB\",\"SiteAddress\":"
+ null + ",\"ZipCode\":" + null + "}]}";
JSONObject objJsonObject = new JSONObject(inputJson);
JSONArray objJsonArray = objJsonObject.getJSONArray("Items");
String csv = CDL.toString(objJsonArray);
FileUtils.writeStringToFile(new File(System.getenv("HOME")+ "/temp.csv"), csv);
}
我使用帶有 UTF-8 編碼的 libreoffice v5.1 打開了 csv 文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.