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
9,984 views
which jar files are requird to execute above code

Hey, @Ramakrishna,

Could you please tell me why you need jar files? I mean are you getting any error using this code?

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 7, 2018 by Omkar
• 69,220 points

selected Aug 7, 2018 by Vardhan
csvMapper.readerFor() is giving the error

Hey, @Ram, 

You can go through this https://www.edureka.co/community/61291/getting-below-error-method-readerfor-undefined-csvmapper. I hope this will be helpful. If not them let me know.

Related Questions In Java

0 votes
1 answer

how to read csv file form sftp connection and store into string object in java code and convert into json.....post it using rest api

Hey, @Pooja, Before starting with anything you should ...READ MORE

answered May 13, 2020 in Java by Roshni
• 10,480 points
3,829 views
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 Aug 21, 2019 in Java by Sirajul
• 59,230 points
3,260 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,190 points
6,995 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,920 points
6,017 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 Aug 20, 2019 in Java by Sirajul
• 59,230 points
2,311 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,140 points
4,015 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 10, 2018 in Java by samarth295
• 2,220 points
888 views
+17 votes
25 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, 2019 in Java by Suresh
• 720 points
253,619 views
+11 votes
13 answers

Default parameters of XMS and XMX in JVM

Run this code to see all the ...READ MORE

answered Nov 13, 2018 in Java by anonymous
402,650 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP