I have a JSONArray like this ->
[
{ "Name" : "Test1", "Age" : 10, "Gender" : "M", "Description" : "Hello World" },
{ "Name" : "Test2", "Age" : 21, "Gender" : "M", "Description" : "Bye\nWorld" }
]
I need to convert this into a csv format. I was using org.json.CD to achieve this like so
String csv = CDL.toString(arr); where arr is the JSONArray as given above. The generated csv string is Name,Age,Gender,Description\nTest1,12,M,Hello World\nTest2,21,M,Bye\nWorld. The csv output of this would be something like this
Name,Age,Gender,Description
Test1,12,M,Hello World
Test2,21,M,Bye
World
But that is not the correct conversion. The correct conversion would have been
Name,Age,Gender,Description
Test1,12,M,Hello World
Test2,21,M,Bye\nWorld
There is no way to manually change this string Name,Age,Gender,Description\nTest1,12,M,Hello World\nTest2,21,M,Bye\nWorld to something like Name,Age,Gender,Description\nTest1,12,M,Hello World\nTest2,21,M,Bye\\nWorldHow do I solve this problem?
PS The values in the JSONArray(name, age, gender, description) are not fixed. I am looking for a way to solve a problem like so in a generic fashion
解决方案
Instead of generating CSV data "manually" use CSV parser (like OpenCSV) to generate it for you. This way instead of
Test2,21,M,Bye
World
you will get format like
Test2,21,M,"Bye
World"
or
"Test2","21","M","Bye
World"
which same parser will be able to properly read back to original data.
DEMO:
//writing CSV
StringWriter sw = new StringWriter();//to create String for demonstration purpose
CSVWriter csvWriter = new CSVWriter(sw);
String[] array = {"Test2","21","M","Bye\nWorld"};
csvWriter.writeNext(array,false);
String csvString = sw.toString();
System.out.println(csvString);
//reading CSV
CSVReader csvReader = new CSVReader(new StringReader(csvString));
//in case of many lines
for (String[] line : csvReader){//in case of many lines
for (String cell : line){//handle each line
System.out.print("");
}
System.out.println();
}
Output:
Test2,21,M,"Bye
World"
<21>
World>
As you see
"Bye
World"
is properly interpreted as single cell with line separator character (\n) and was able to be print as
World>