Pages

Friday 7 March 2014

Convert CSV File to JSON Object in JAVA


Here i would like to share that how to convert a csv file contents to JSON object  in JAVA

Included Libraries

<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.3.4</version>
</dependency>

Sample Code


package com.test.csvtojson;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

/**
 *
 * @author Jamsheer T +91 9846716175
 */
public class CSVtoJson {

public static void main(String[] args) { int i; String line = ""; String fileToParse = "C:\\Users\\Jamsheer T\\Desktop\\csv\\ex.csv"; BufferedReader fileReader = null; boolean initial = true; ArrayList<String> header = new ArrayList<String>(); JSONObject record = new JSONObject(); try { fileReader = new BufferedReader(new FileReader(fileToParse)); while ((line = fileReader.readLine()) != null) { i = 0; String[] tokens = line.split(","); if (initial) { for (String token : tokens) { if (token.startsWith("\"")) { token = token.substring(1); } if (token.endsWith("\"")) { token = token.substring(0, token.length() - 1); } header.add(token); } initial = false; continue; } // Get all tokens available in line for (String token : tokens) { if (token.startsWith("\"")) { token = token.substring(1); } if (token.endsWith("\"")) { token = token.substring(0, token.length() - 1); } record.put(header.get(i).toString(), token); i++; if (i == header.size()) break; } System.out.println(record); } } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } }

No comments:

Post a Comment