How can we ignore the comma's inside barces while converting csv into bean or string array in java

 

问题

https://stackoverflow.com/questions/68413018/how-can-we-ignore-the-commas-inside-barces-while-converting-csv-into-bean-or-st

Below is the sample CSV file, Im trying to convert to java bean/string[],

ID,NAME,DEP_DETAILS,REG_NO

P7-3001,JOHN,{"head_dep":"[{\"dep\":\"CS\",\"update_time\":\"2021-06-17T07:29:40.800Z\"}]","LN":false},009988

RT-9008,RIK,{"head_dep":"OPEN","dep_type":"S7"},889912

In the sample data, I want to read DEP_DETAILS in whole by ignoring comma's inside braces,

DEP_DETAILS is {"head_dep":"[{"dep":"CS","update_time":"2021-06-17T07:29:40.800Z"}]","LN":false} in 1st row and {"head_dep":"OPEN","dep_type":"S7"} in 2nd row

so for example expected output of the 1st row will be,

- [0] = P7-3001,JOHN

- [1] = JOHN

- [2] = {"head_dep":"[{\"dep\":\"CS\",\"update_time\":\"2021-06-17T07:29:40.800Z\"}]","LN":false}

- [3] = 889912

how can I ignore the comma's inside the brace and take whole as string.

Is there any possibilities using openCsv or any?

解答

这个问题需要将非标准格式的csv 中有逗号的 json 串解析为一个完整的字符串。Java 实现则代码较长。

Java 下的开源包 SPL 很容易写,只要 1 句:


A

1

=file("json.csv").import@cpt(ID,NAME,DEP_DETAILS:string,REG_NO)

SPL提供了JDBC 供 Java 调用,把上面的脚本存为parseCsv.splx,在 Java 中以存储过程的方式调用脚本文件:

Class.forName("com.esproc.jdbc.InternalDriver");

con= DriverManager.getConnection("jdbc:esproc:local://");

st=con.prepareCall("call parseCsv ()");

st.execute();

或在Java 中以 SQL 方式直接执行 SPL 串:

st = con.prepareStatement("==file(\"json.csv\").import@cpt(ID,NAME,DEP_DETAILS:string,REG_NO)");
st.execute();

SPL 源代码:https://github.com/SPLWare/esProc

问答搜集