How to ESCAPE delimiter character in Jackson-dataformat-csv library?

5.3k views Asked by At

My use case was to convert an Java POJO into String so it can be passed to be published to AWS Kinesis Firehose Stream.

I was writing this convertToString(), but I'm unable to find the correct way to escape delimiter.

public <T> List<String> convertToString(List<T> objectList, Class<T> tClass) {

        List<String> stringList = new ArrayList<>();
        char delimiter = ',';
        char escape = '\\';

        CsvMapper mapper = new CsvMapper();
        CsvSchema schema = mapper.schemaFor(tClass);

        for (T object : objectList ) {
            try{
                stringList.add(mapper.writer(schema.withColumnSeparator(delimiter).withEscapeChar(escape))
                        .writeValueAsString(object));
            } catch (JsonProcessingException e) {
                System.out.println("Exception : " + e);
            }
        }

        return stringList;
}

Input : SuperHero flash = new SuperHero(1, "Flash", "Barry , Allen", "DC");

Expected Output : 1,Flash,"Barry \, Allen",DC

Output I'm getting : 1,Flash,"Barry , Allen",DC

Can someone point what I'm doing wrong?

1

There are 1 answers

4
Zaid Qureshi On

Your output is correct, in CSV when you surround an object or element with double quotes it is written as is, so "Flash" is written without quotes, and "Barry ,Allen" is written with quotes in the output, therefore the delimiter is already escaped and doesn't need to be escaped with the back slash.

EDIT/UPDATE

After reading the documentation provided on github, the following line shows generator only uses double quotes, and escape is only used for parsing.

escapeChar (int) [default: -1 meaning "none"]: character, if any, used to escape values. Most commonly defined as backslash ('\'). Only used by parser; generator only uses quoting, including doubling up of quotes to indicate quote char itself.