使用Java将JSONArray转换为csv [英] Converting a JSONArray to csv using java

查看:572
本文介绍了使用Java将JSONArray转换为csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的JSONArray->

I have a JSONArray like this ->

[ 
{ "Name" : "Test1", "Age" : 10, "Gender" : "M", "Description" : "Hello World" }, 
{ "Name" : "Test2", "Age" : 21, "Gender" : "M", "Description" : "Bye\nWorld" }
]

我需要将其转换为csv格式。我正在使用 org.json.CD 来实现这一点,因此
String csv = CDL.toString(arr); 其中 arr 是上面给出的JSONArray。生成的csv字符串是 Name,Age,Gender,Description\nTest1,12,M,Hello World\nTest2,21,M,Bye\nWorld 。 csv的输出将是这样的

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

无法手动更改此字符串名称,年龄,性别,说明\nTest1,12,M,Hello World\nTest2,21,M,Bye\nWorld 改为 Name,Age,Gender,说明\nTest1,12,M,Hello World\nTest2,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 JSONArray中的值(名称,年龄,性别,描述)不固定。我正在寻找一种以通用方式解决此类问题的方法

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

推荐答案

而不是手动生成CSV数据。使用CSV解析器(如OpenCSV)为您生成它。用这种方法代替

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

您将获得以下格式:

Test2,21,M,"Bye
World"

"Test2","21","M","Bye
World"

同一解析器将能够正确读取回原始数据。

which same parser will be able to properly read back to original data.

演示:

//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("<"+cell + ">");
    }
    System.out.println();
}

输出:

Test2,21,M,"Bye
World"

<Test2><21><M><Bye
World>

如您所见

"Bye
World"

正确地解释为单个单元格,带有行分隔符( \n )并可以打印为

is properly interpreted as single cell with line separator character (\n) and was able to be print as

<Bye
World>

这篇关于使用Java将JSONArray转换为csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆