I'm doing a converter from json to csv file. I've tried a solution from this link but it doesn't work properly: Converting JSON to XLS/CSV in Java
The problem is that I don't have data in separate columns and also I have names of columns in different order. Is it possible to fix this?
My json looks like this:
{
"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.
My code:
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();
}
}
results(first expected):
working as you expect using the below code. I don't see any major difference between your and my code....
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);
}
i opened the csv file using libreoffice v5.1 with UTF-8 encoding
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.