Search code examples
javaopencsv

CSVReader treart null as string "null"


I have a input csv like below

firstName,lastName
abdu,null
shah,kha

I am using opencsv and my code is like

File inputFile = new File("input.csv");
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator<Map<String, String>> mappingIterator = 
        new CsvMapper().readerFor(Map.class).with(schema).readValues(inputFile);

The first mapping iterator results in map with firstName and lastName as keys. The lastName has value as "null" (quoted string). Is there way by which I could read it as null (without quotes)??


Solution

  • in OpenCSV you can implement your own CSVParser like this:

    public static void main(String[] args) throws Exception {
        String csv = "firstName,lastName\n" +
                "abdu,null\n" +
                "shah,kha";
    
        CSVReader reader = new MyCSVReader(csv);
    
        String[] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            for (String s : nextLine) {
                System.out.print(s == null ? "NULL" : s);
            }
            System.out.println();
        }
    }
    
    private static class MyCSVReader extends CSVReader {
        public MyCSVReader(String csv) {
            super(new StringReader(csv));
            parser = new CSVParser() {
                @Override
                protected String[] parseLine(String nextLine, boolean multi) throws IOException {
                    String[] result = super.parseLine(nextLine, multi);
                    for (int i = 0; i < result.length; ++i) {
                        if ("null".equals(result[i])) result[i] = null;
                    }
                    return result;
                }
            };
        }
    }