0

If our JSON data consists only of flat, one-dimensional data, how can convert those data by iterating over your outer objects and building a CSV line by concating the string values of your inner objects.

Could anyone provide with example please?

kumar
  • 355
  • 2
  • 4
  • 9
  • There are plenty of examples available online, based on how your JSON is formatted - you can refer to examples as like this https://vcfvct.wordpress.com/2015/06/30/converting-nested-json-files-to-csv-in-java-with-reflection/ – N00b Pr0grammer Feb 11 '16 at 09:58

1 Answers1

0

You can try this :

import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class toCSV {
  public static void main(String args[]){
     String jsonString = "{\"infile\": [{\"field1\": 11,\"field2\": 12,\"field3\": 13},{\"field1\": 21,\"field2\": 22,\"field3\": 23},{\"field1\": 31,\"field2\": 32,\"field3\": 33}]}"

     JSONObject output = new JSONObject(jsonString);
     JSONArray docs = response.getJSONArray("infile");

     File file=new File("C:/JsontoCSVExample.csv");
     String csv = CDL.toString(docs);
     FileUtils.writeStringToFile(file, csv);
  }
}

The maven dependency was like,

 <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20090211</version>
</dependency>

Also, You can take ref. from here

Community
  • 1
  • 1
Niks
  • 175
  • 7