0

Problem is let's say the parameter Json String is

{
  "FIRST_NAME":"Bob",
  "LAST_NAME": "Tuna"
}

in my myCsvHeaders.getList() method in the for loop, I would have to make 2 variables (basically matching the json key names, case sensitive so it knows to retrieve those data for this specific column)

String FIRST_NAME
String LAST_NAME

Once it writes the .csv file the headers/column will be FIRST_NAME LAST_NAME.

But, is there a way to change the headers to what I want ie. "First Name" "Last Name".

public void jsonToCsv(String json) {
ObjectMapper om = new ObjectMapper();
try {
    JsonNode jsonTree = om.readTree(json);
    Builder csvSchemaBuilder = CsvSchema.builder();
    
    // myCsvHeaders.getList() is basically list of Strings of headers I want
    for(String csvHeaders : myCsvHeaders.getList()) {
        csvSchemaBuilder.addColumn(csvHeaders);
    }

    CsvSchema csvMapper= csvSchemaBuilder.build().withHeader();
    csvMapper.enable(JsonGenerator.Feature.IGNORE_UNKNOWN);
    csvMapper.writerFor(JsonNode.class)
    .with(csvSchema)
    .writeValue(new File("randomlocation/test.csv"), jsonTree);
    catch(Exception e) {
    e.printStackTrace();
    }

   }
}
rairai
  • 21
  • 6

0 Answers0