我正在做一个从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();
}
}
结果(首次预期):
答案 0 :(得分:0)
使用以下代码按预期工作。我发现你和我的代码之间没有任何重大差异......
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文件