我的字符串为:
String cont = "[[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,13.46,\"1682432\"]," +
"[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-13.46,\"1682432\"]," +
"[\"START\",\"1001\",\"\",\"\",\"2014-07-15\",\"Invoice\",0,-14.52,\"1682432\"]," +
"[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FICA and\",-13.46,0,\"1682432\"]," +
"[\"START\",\"6002\",\"020\",\"0000000PWO\",\"2014-07-15\",\"MY Comment - FEED\",-1.06,0,\"1682432\"]" +
"]";
我需要输出为
Account || Date || Amount || Description || InvoiceNo
1001 2014-07-15 -13.46 1682432
....some more data
6002 2014-07-15 -1.06 MY desc 1682432
我正在尝试使用版本 2.3 的 Apache CSV 解析器。
<dependency>
<groupId>net.sf.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>2.3</version>
</dependency>
java代码:
CSVReader reader = new CSVReader(new StringReader(cont), ',');
List<String[]> records = reader.readAll();
Iterator<String[]> iterator = records.iterator();
while (iterator.hasNext()) {
String[] record = iterator.next();
for (String string : record) {
System.out.println(string);
}
}
输出:
[[START
1001
2014-07-15
...
["START
6002
020
0000000PWO
2014-07-15
MY Comment - FEED
-1.06
0
1682432"]]
1) 如何删除特殊字符“[”和“]”
2) 如何为上述输出字段赋值
3)我想将上面的csv转换为bean对象
4)bean 到 json
最佳答案
您可以利用开源库uniVocity-parsers将csv转换为bean对象,如以下代码所示:
public static void main(String[] args) throws FileNotFoundException {
/**
* ---------------------------------------------
* Read CSV rows into list of beans you defined
* ---------------------------------------------
*/
// 1st, config the CSV reader with row processor attaching the bean definition
BeanListProcessor<ColumnBean> rowProcessor = new BeanListProcessor<ColumnBean>(ColumnBean.class);
settings.setRowProcessor(rowProcessor);
settings.setHeaderExtractionEnabled(true);
// 2nd, parse all rows from the CSV file into the list of beans you defined
parser.parse(new StringReader(cont));
List<ColumnBean> resolvedBeans = rowProcessor.getBeans();
// 3rd, process the beans with business logic
// ......
}
使用该库,您只需要几行代码,并且它还提供了显着的性能。在其 Homepage. 中查找教程
根据bean对象到json的转换,您可以检查Google Gson project.
关于java csv多数据解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25314664/