1

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"
3
  • Have you tried openCSV? I cannot supply you a link at the moment because they're migrating to a new datacenter, but they have a CSV parser Commented Feb 15, 2018 at 17:05
  • Can you provide and example of the CSV data you will be parsing as how the nested address and subject will influence the solution Commented Feb 15, 2018 at 17:08
  • The answer to this is "use a JSON library" (or "use a CSV library", depending on which of the two halves of the question you answer) -- and because of that, it's effectively an off-topic "Please recommend a library" question. Commented Feb 15, 2018 at 17:11

1 Answer 1

3

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> 
Sign up to request clarification or add additional context in comments.

4 Comments

is this will work any type of csv format ? can you tell me the format of csv to have nested json string as output.
im getting below exception when i tried in reverese way.. json to csv. JsonMappingException: CSV generator does not support Object values for properties (through reference chain: csvparser.User["address"])
This code cannot read the CSV sample as the JSON sample given in the question. It does not bother nesting the objects. It simply converts the CSV to that: (only the 1st row is shown below for simplicity) { "studentName" : "Foo", "Age" : "12", "address__city" : "newyork", "address__address1" : "North avenue", "address__zipcode" : "123213", "subjects__name" : "English", "subjects__marks" : "40" }
Not a solution for the question asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.