Search code examples
javacsvfileexport-to-csvexport-to-excel

How to write an object containing json values into a csv file in java?


I am having an object myData which is having 100's json records like :

[Record{Purpose='Medical ', Date='2020-10-14', ID='9215524400  ', UpdateTime='2020-10-14', Checkin='2020-10-14'},...] 

I need to write it into a csv file in proper csv format.

Here is my code :

   FileWriter csvWriter = new FileWriter("myFilecsv.csv");
   csvWriter.write(String.valueOf(myData)); //Its writing the file as a String

I tried to convert it using the below code :

        JFlat flatMe = new JFlat(str);
        //To get the 2D representation
        flatMe.json2Sheet().headerSeparator("_").getJsonAsSheet();
        //write the 2D representation in csv format
        flatMe.write2csv("myFilecsv.csv");

This is throwing error :

 java.lang.ClassNotFoundException: com.jayway.jsonpath.Configuration$Defaults

I am using below dependencies

   <dependency>
        <groupId>com.github.opendevl</groupId>
        <artifactId>json2flat</artifactId>
        <version>1.0.3</version>
    </dependency>
    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.0.0</version>
        <scope>test</scope>
    </dependency>

Is there a better way to achieve this ? Please let me know :


Solution

  • Adding the jar json2flat-1.0.3.jar resolved the issue.