Parse csv data and convert to nested json java

I'm searching for simplest way or any jar available to read csv file in java and convert to into nested json. I tried searching for various sources, but all the places i could find results for simple json, but my need is i should read csv file which later has to be converted to json string in the below format

{
    "studentName": "Foo",
    "Age": "12",
    "address":{
        "city" : "newyork",
        "address1": "North avenue",
        "zipcode" : "123213"
    },
    "subjects": [
        {
            "name": "English",
            "marks": "40"
        },
        {
            "name": "History",
            "marks": "50"
        }
    ]
}

I'm fine with any format in csv, however after reading csv file i need to create json string like above.

csv file format:

"studentName","Age","address__city","address__address1","address__zipcode","subjects__name","subjects__marks"
"Foo","12","newyork","North avenue","123213","English","40"
"","","","","","History","50"

Upvotes: 1

Views: 7206

Answers (1)

Md Johirul Islam
Md Johirul Islam

Reputation: 5162

You can use JackSon to convert CSV to JSON. For example see the following code:

import java.io.File;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

public class CSV2JSON {

    public static void main(String[] args) throws Exception {
        File input = new File("input.csv");
        File output = new File("output.json");

        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();

        // Write JSON formated data to output.json file
        mapper.writerWithDefaultPrettyPrinter().writeValue(output, readAll);

        // Write JSON formated data to stdout
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(readAll));
    }
}

If you are using maven you can add the Jackson dependency as following:

   <dependency>
     <groupId>com.fasterxml.jackson.core</groupId>
     <artifactId>jackson-databind</artifactId>
     <version>2.8.9</version>
   </dependency>
   <dependency>
     <groupId>com.fasterxml.jackson.dataformat</groupId>
     <artifactId>jackson-dataformat-csv</artifactId>
     <version>2.8.9</version>
   </dependency> 

Upvotes: 3

Related Questions