0

I want to upload a CSV file from html page and then in the java controller want to convert it to Model Object.

I am using the following approach:

ICsvBeanReader beanReader = null;
    try {
        beanReader = new CsvBeanReader(new InputStreamReader(file.getInputStream()),
                CsvPreference.STANDARD_PREFERENCE);

        // the header elements are used to map the values to the bean (names
        // must match)
        final String[] header = beanReader.getHeader(true);
        // get Cell Processor
        final CellProcessor[] processors = getProcessors();

        CSVData csvData;
        while ((csvData = beanReader.read(CSVData.class, header, processors)) != null) {
            System.out.println(csvData);
        }
    } catch (Throwable t) {
        t.printStackTrace();
    }


    private static CellProcessor[] getProcessors() {

    final CellProcessor[] processors = new CellProcessor[] {
            new NotNull(), // CustomerId
            new NotNull(), // CustomerName
            new NotNull(),
            new NotNull(),
            new NotNull(),
            new NotNull(new ParseInt()),
            new NotNull(new ParseInt()),
            new NotNull(new ParseInt()),
            new NotNull(new ParseDouble()),
            new NotNull(),
            new NotNull()



    };
    return processors;
}

This is working for fields having no white spaces like msgID .But it is failing for fields with white spaces like MSG DATA . It is giving error for fields like MSG DATA as follows:

org.supercsv.exception.SuperCsvReflectionException: unable to find method setMSG DATA(java.lang.String) in class com.springboot.dto.CSVData - check that the corresponding nameMapping element matches the field name in the bean, and the cell processor returns a type compatible with the field context=null

Thanks

Tarun
  • 271
  • 1
  • 6
  • 18
  • You can use this answer : https://stackoverflow.com/questions/53480525/how-to-provide-a-custom-deserializer-with-jackson-and-spring-boot/53481767#53481767 – Pawan Tiwari Nov 27 '18 at 11:00
  • Your answer converts json to object and vice-versa. I hav to upload the CSV and in the java controller I am receiving bytes . So I need to convert bytes to java dto. – Tarun Nov 27 '18 at 12:12
  • You need to just pass your csv object and the class name in which you want to convert your data. – Pawan Tiwari Nov 27 '18 at 12:24

1 Answers1

0

For making this code work, changes were required to the following piece of code:

final String[] header = beanReader.getHeader(true);

Here as it is reading the headers from the csv file so it is not able to find the setters for them in the model file. Here the name of our model class fields can be passed as follows:

final String[] header = {"msgID" , "msgData" , "dataUnits" ...}

Now it will be able to locate the setters for these header fields in the model file and thus parse the CSV in to the model file.

Tarun
  • 271
  • 1
  • 6
  • 18