Convert CSV to JSON. JSON payload should be included in square brackets

+1 vote

Hi Experts

I have a requirement to convert CSV to JSON. Assume if CSV files have got 2 rows. I need to create a JSON file for each row. This means output will be 2 json files.

Sample Test data: Test.csv

ID,fileName,Type,Direction,Date
1001,File1,PDF,Out,20180518
1002,File2,DOC,Out,20180502
 

I have written below code for achieving this. The code is working fine and creating individual JSON files for each row as:

File1.txt

{
  "ID" : "1001",
  "fileName" : "File1",
  "Type" : "PDF",
  "Direction" : "Out",
  "Date" : "20180518"
}

File2.txt

{
  "ID" : "1002",
  "fileName" : "File2",
  "Type" : "DOC",
  "Direction" : "Out",
  "Date" : "20180502"
}

I need to include the JSON payload in square brackets as root. E.g. Output should be as below. How can I achieve this

File1.txt

[

{
  "ID" : "1002",
  "fileName" : "File2",
  "Type" : "DOC",
  "Direction" : "Out",
  "Date" : "20180502"
}

]

File2.txt

[

{
  "ID" : "1002",
  "fileName" : "File2",
  "Type" : "DOC",
  "Direction" : "Out",
  "Date" : "20180502"
}

]

Code:

package com.sap.csv2json;

import java.io.File;

import java.util.List;

import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.SerializationFeature;

import com.fasterxml.jackson.dataformat.csv.CsvMapper;

import com.fasterxml.jackson.dataformat.csv.CsvSchema;

public class ConvertCSVtoJson {

@SuppressWarnings("unchecked")

public static void main(String[] args) throws Exception {

        File input = new File("C:\\Users\\akellap\\RND\\JSON\\Source\\Test.csv");

        CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();

        CsvMapper csvMapper = new CsvMapper();

        // Read data from CSV file

        List<Object> readAll = csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll();

                    ObjectMapper mapper = new ObjectMapper();

        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        // Write JSON formated data to output.json file

           for (Object row : readAll) {

        Map<String, String> map = (Map<String, String>) row;

        String fileName = map.get("fileName");

        File output = new File("C:\\Users\\akellap\\RND\\JSON\\Target\\"+fileName+".txt");

         mapper.writerWithDefaultPrettyPrinter().writeValue(output, row);

                }

          }

}

Aug 4, 2018 in Java by phaniakella
• 160 points
903 views

1 answer to this question.

+1 vote
Best answer

The JSON payload uses a list and so to have square brackets in your output file, you need to convert the data of arrays into list using the following code:

Arrays.asList(arrayofdata);

So the complete code should look like this:

package com.sap.csv2json;

import java.io.File;

import java.util.List;

import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;

import com.fasterxml.jackson.databind.SerializationFeature;

import com.fasterxml.jackson.dataformat.csv.CsvMapper;

import com.fasterxml.jackson.dataformat.csv.CsvSchema;


public class ConvertCSVtoJson {

@SuppressWarnings("unchecked")

public static void main(String[] args) throws Exception {

        File input = new File("C:\\Users\\akellap\\RND\\JSON\\Source\\Test.csv");

        CsvSchema csvSchema = CsvSchema.builder().setUseHeader(true).build();

        CsvMapper csvMapper = new CsvMapper();

        // Read data from CSV file

        List<Object> readAll = Arrays.asList(csvMapper.readerFor(Map.class).with(csvSchema).readValues(input).readAll());

                    ObjectMapper mapper = new ObjectMapper();

        mapper.enable(SerializationFeature.INDENT_OUTPUT);

        // Write JSON formated data to output.json file

           for (Object row : readAll) {

        Map<String, String> map = (Map<String, String>) row;

        String fileName = map.get("fileName");

        File output = new File("C:\\Users\\akellap\\RND\\JSON\\Target\\"+fileName+".txt");

         mapper.writerWithDefaultPrettyPrinter().writeValue(output, row);

                }

          }

}

And the output file will be as follows:



 

answered Aug 6, 2018 by Omkar
• 67,290 points

selected Aug 6, 2018 by Vardhan

Related Questions In Java

0 votes
2 answers

How to convert a JSON String into Object in Java?

You could probably check out Google's Gson: ...READ MORE

answered 3 days ago in Java by Sirajul
• 19,670 points
256 views
0 votes
1 answer

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?

You can use: new JSONObject(map); READ MORE

answered Jun 27, 2018 in Java by Akrati
• 3,150 points
1,705 views
0 votes
2 answers

How do we convert JSON to Map in Java

When you don't know structure of json. ...READ MORE

answered Oct 31, 2018 in Java by Sushmita
• 6,870 points
145 views
0 votes
2 answers

How can I convert a String variable to a primitive int in Java

 Here are two ways illustrating this: Integer x ...READ MORE

answered 4 days ago in Java by Sirajul
• 19,670 points
112 views
0 votes
3 answers

How to parse JSON in Java

import org.json.*; JSONObject obj = new JSONObject(" .... ...READ MORE

answered Aug 20, 2018 in Java by Daisy
• 8,050 points
1,386 views
0 votes
2 answers
0 votes
2 answers

How to convert array into list in Java?

Another workaround if you use apache commons-lang: int[] ...READ MORE

answered Aug 9, 2018 in Java by samarth295
• 2,190 points
43 views
0 votes
3 answers

How to convert File to Byte[] in Java?

import java.io.File; import java.nio.file.Files; File file; // ...(file is initialised)... byte[] ...READ MORE

answered Aug 14, 2018 in Java by samarth295
• 2,190 points
61 views
+14 votes
18 answers

How can I convert String to JSON object in Java?

Hi @Daisy You can use Google gson  for more ...READ MORE

answered Feb 7 in Java by Suresh
• 700 points
72,686 views
+7 votes
11 answers

Default parameters of XMS and XMX in JVM

You use these Java command-line parameters to ...READ MORE

answered Nov 13, 2018 in Java by Murali
88,612 views