Converting an CSV file to a JSON object in Java

前端 未结 9 1678
太阳男子
太阳男子 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:44

    If you're using Java 8, you can do something like this. No Libraries or complicated logic required.

    Firstly, create a POJO representing your new JSON object. In my example it's called 'YourJSONObject' and has a constructor taking two strings.

    What the code does is initially reads the file, then creates a stream of String based lines. ( a line is equivalent to a line in your CSV file).

    We then pass the line in to the map function which splits it on a comma and then creates the YourJSONObject.

    All of these objects are then collected to a list which we pass in to the JSONArray constructor.

    You now have an Array of JSONObjects. You can then call toString() on this object if you want to see the text representation of this.

            JSONArray objects = new JSONArray(Files.readAllLines(Paths.get("src/main/resources/your_csv_file.csv"))
                .stream()
                .map(s -> new YourJSONObject(s.split(",")[0], s.split(",")[1]))
                .collect(toList()));
    

提交回复
热议问题