java json csv,使用Java将JSONArray转换为csv

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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值