1

I am searching for java library that can convert csv data which consists nested objects (like : address.city, address.country) to convert into json data with nested objects accordingly. Below is the java code i am using:

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();
    System.out.println(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));

This is the output i am getting:

[ {
 "studentName" : "Foo",
 "Age" : "12",
 "address__city" : "newyork",
 "address__address1" : "North avenue",
 "address__zipcode" : "123213",
 "subjects__name" : "English",
 "subjects__marks" : "40"
  }, {
 "studentName" : "ABcd",
 "Age" : "25",
 "address__city" : "achi",
 "address__address1" : "Morh",
 "address__zipcode" : "27400",
 "subjects__name" : "History",
 "subjects__marks" : "50"
 } ]

This is expected output:

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

This is input csv:

"studentName","Age","address__city","address__address1","address__zipcode","subjects__name","subjects__marks"
"Foo","12","newyork","North avenue","123213","English","40"
"","25","achi","Morh","2400","History","
MuKaz
  • 61
  • 5
  • [https://stackoverflow.com/questions/19766266/directly-convert-csv-file-to-json-file-using-the-jackson-library] – shas Aug 17 '18 at 08:12
  • Thanks for the time @shas, but i am still getting the same output as it was... i am not getting the expected output... – MuKaz Aug 17 '18 at 11:20

1 Answers1

0

It looks like univocity-parsers can do what you need on the CSV side with its @Nested annotation.

It doesn't work to read/write JSON though. So my advice is to use univocity parsers to parse your CSV into the object structure you need, then Jackson to write that object structure into JSON.

Hope this helps. Disclosure: I'm the author of univocity-parsers. It's open-source and free (Apache 2.0 license)

Jeronimo Backes
  • 6,141
  • 2
  • 25
  • 29