I am trying to convert CSV into JSON and using OpenCSV and trying to add attributes of JSON from CSV header. For that, I am extracting first row from CSV into separate array and then processing the remaining CSV and adding it to JSON. But it's not writing in JSON in the same sequence as that of CSV.
For Example: CSV
name,address,phone
john,palo alto, 999
michael, SFO, 4342
And the JSON i get is:
[
{
"address" : palo alto,
"name" : john,
"phone" : 999
},
{
"address" : SFO,
"name" : michael,
"phone" : 4342
},
......
......
]
Here is my java code:
// Iterate through the rows.
CSVReader reader = null;
try {
fr = new FileReader(csvFile);
// create a new CSV reader
reader = new CSVReader(fr, ',', '"', 0);
// Read all rows at once
List<String[]> allRows = reader.readAll();
// store the header field from CSV to be used to define properties
// like name, address, contact etc
String[] header = allRows.get(0);
// Read CSV line by line and use the string array as you want
for (int j = 1; j < allRows.size(); j++) {
String[] row = allRows.get(j);
JSONObject cells = new JSONObject();
int i = 0;
for (; i < row.length; i++) {
String cellValue = row[i];
cells.put(header[i], cellValue);
}
//write to JSON array
json.put(cells);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} catch (JSONException e) {
} finally {
try {
reader.close();
fr.close();
} catch (IOException e) {
}
}
UPDATE: I am displaying the JSON data over UI in table using javascript. JSON data is returned as the response. Have to display in particular table order.