Posted In: Java Core, JSON

Converting JSON to CSV in Java using Arkni – json-to-csv

Download org.jsontocsv.parser.JSONFlattener from Arkni – json-to-csv


package com.example.csv;

import java.util.List;
import java.util.Map;

import org.jsontocsv.parser.JSONFlattener;
import org.jsontocsv.writer.CSVWriter;
import org.junit.Test;

public class JsonToCsv2 {

	@Test
	public void jsontocsv() throws Exception {
		System.out.println("jsontocsv started");
		try {
			List> flatJson = JSONFlattener
			        .parseJson(jsonString());
			CSVWriter.writeToFile(CSVWriter.getCSV(flatJson, ","),
			        "E:/files/outcsv1.csv");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static String jsonString() {
		return "[" + "    {" + "        \"studentName\": \"Foo\","
		        + "        \"Age\": \"12\"," + "        \"subjects\": ["
		        + "            {" + "                \"name\": \"English\","
		        + "                \"marks\": \"40\"" + "            },"
		        + "            {" + "                \"name\": \"History\","
		        + "                \"marks\": \"50\"" + "            }"
		        + "        ]" + "    }" + "]";
	}

}

Result

studentName,subjects[1].name,subjects[1].marks,subjects[2].name,subjects[2].marks,Age
Foo,English,40,History,50,12

Tags:

by , on August 31st, 2017

  • Categories