Converting an CSV file to a JSON object in Java

前端 未结 9 1692
太阳男子
太阳男子 2020-12-05 21:47

Is there an open source java library to convert a CSV (or XLS) file to a JSON object?

I tried using json.cdl, but somehow it does not seem to work for large CSV stri

9条回答
  •  佛祖请我去吃肉
    2020-12-05 22:46

    With Java 8, writing JSON is at hand.

    You didn't specify what JSON API you want, so I assume by "JSON object" you mean a string with a serialized JSON object.

    What I did in the CSV Cruncher project:

    1. Load the CSV using HSQLDB. That's a relatively small (~2 MB) library, which actually implements a SQL 2008 database.
    2. Query that database using JDBC.
    3. Build a JDK JSON object (javax.json.JsonObject) and serialize it.

    Here's how to do it:

    static void convertResultToJson(ResultSet resultSet, Path destFile, boolean printAsArray) 
    {
                OutputStream outS = new BufferedOutputStream(new FileOutputStream(destFile.toFile()));
                Writer outW = new OutputStreamWriter(outS, StandardCharsets.UTF_8);
    
                // javax.json way
                JsonObjectBuilder builder = Json.createObjectBuilder();
                // Columns
                for (int colIndex = 1; colIndex <= metaData.getColumnCount(); colIndex++) {
                    addTheRightTypeToJavaxJsonBuilder(resultSet, colIndex, builder);
                }
                JsonObject jsonObject = builder.build();
                JsonWriter writer = Json.createWriter(outW);
                writer.writeObject(jsonObject);
    

    The whole impl is here. (Originally I wrote my own CSV parsing and JSON writing, but figured out both are complicated enough to reach for a tested out-of-the-shelf library.)

提交回复
热议问题