【问题标题】:Converting CSV to JSON without ANT or Maven在没有 ANT 或 Maven 的情况下将 CSV 转换为 JSON
【发布时间】:2013-02-14 10:12:41
【问题描述】:

我试图将 CSV 文件转换为 JSON 格式,但我不知道 ANT 或 MAVEN。我使用过 Apache POI。我正在尝试使用 Apache POI 来做到这一点。有没有其他方法可以做到这一点?

这就是我试图做的,但得到以下错误 --java.lang.ClassNotFoundException: org.openxmlformats.schemas.spreadsheetml.x2006.main.CTSheet

// 开始构造 JSON。

    JSONObject json = new JSONObject();
    JSONArray rows=new JSONArray();

    for ( Iterator<org.apache.poi.ss.usermodel.Row> rowsIT = sheet.rowIterator(); rowsIT.hasNext(); )
    {
        org.apache.poi.ss.usermodel.Row row = rowsIT.next();
        JSONObject jRow = new JSONObject();

        // Iterate through the cells.
        JSONArray cells = new JSONArray();
        for ( Iterator<Cell> cellsIT = row.cellIterator(); cellsIT.hasNext(); )
        {
            Cell cell = cellsIT.next();
            cells.put( cell.getStringCellValue() );
        }
        jRow.put( "cell", cells );
        rows.put( jRow );
    }

【问题讨论】:

  • 是的,还有另一种方法可以做到这一点。问题已回答。
  • 请发布您的 CSV 标头,我为您制作了二十行代码...

标签: java javascript json apache-poi


【解决方案1】:

简单的CSV可以通过简单的java编码转换成Json如下

首先使用加载文件

BufferedReader.readLine()

然后使用

String.split(",") // to get the value from each line

并使用

将每个值写入输出
BufferedWriter //  with the necessary JSON braces and quoting

【讨论】:

  • 这种方法很容易导致严重的解析错误。例如,记录的分隔符可能不是newline。此外,还有可能引用/转义的分隔符字符。另一方面,引号字符也可以在带引号的单元格中进行转义。无论如何,我建议为此使用复杂的框架。
  • @Sri Apache Commons library for CSV 怎么样?
【解决方案2】:

我得到了我的问题的答案,我阅读了我的 CSV usig BufferReader 并通过使用将其转换为 JSON http://code.google.com/p/google-gson/

【讨论】:

    猜你喜欢
    • 2017-05-20
    • 2012-11-21
    • 2017-04-05
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多