Posted In: Java Core, JSON

Converting JSON to CSV in Java using org.json.CDL

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

Example first reads file and the creates JSONArray. After that it again creates CSV string and writes to a CSV file.

Please note order of keys will not remain constant as JSON is un-ordered collection.
SYMBOL,SERIES,OPEN,HIGH,LOW,CLOSE,LAST,PREVCLOSE,TOTTRDQTY,TOTTRDVAL,TIMESTAMP,TOTALTRADES,ISIN
20MICRONS,EQ,34.7,34.7,33.9,34,34.2,33.7,15592,532530.3,24-AUG-2017,158,INE144J01027

package com.example.csv;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

import org.apache.commons.io.FileUtils;
import org.json.CDL;
import org.json.JSONArray;
import org.junit.Test;

public class JsonToCsv {

	private StringBuilder sb = new StringBuilder();

	@Test
	public void jsontocsv() throws Exception {
		System.out.println("jsontocsv started");
		String fileNameIn = "E:/files/incsv.csv";
		String fileNameOut = "E:/files/outcsv.csv";
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(fileNameIn));
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			JSONArray array = new JSONArray(
			        CDL.toJSONArray(sb.toString()).toString());
			String csv = CDL.toString(array);
			FileUtils.write(new File(fileNameOut), csv, "UTF-8");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			reader.close();
		}
	}
}

Tags:

by , on August 31st, 2017

  • Categories