Configure CsvMapper to Inspect Each Value Written

Curt Williams :

I am using jackson-dataformat-csv to export a POJO collection to CSV as follows:

CsvSchema.Builder schemaBuilder = CsvSchema.builder()
  .addColumn("id")
  .addColumn("name")
  etc...
CsvSchema schema = schemaBuilder.build().withHeader();
CsvMapper mapper = new CsvMapper();
mapper.enable(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS);
String csv = mapper.writer(schema).writeValueAsString(pojoCollection);

I want to inspect every field value before it is written to CSV and optionally modify that value to prevent formulas or other content that Excel, Sheets, etc might execute. For example if a value starts with @ or = then I might prepend the ' character to that value to prevent execution.

How can I configure CsvMapper so that I get a callback for each value written to CSV?

Antot :

Both CsvGenerator and CsvEncoder, which execute the job of processing values for CSV output, do not seem to include callback options. So I think that the goal is not achievable with jackson.

But of course, this task can be solved through other approaches.

Without using other libraries, pojoCollection can be pre-processed with the aim of sanitizing the string fields. Not knowing the actual structure of these pojos, the choices may be:

  • if the pojos are compact and the fields to process are well known, create a method that expects a reference to a pojo's respective getter and setter as args, invokes the getter to retrieve the value, sanitizes it and sets the clean value. Loop over pojoCollection to process them all.

  • if string fields are numerous and pojos are of different types and they all need to be cleaned, use reflection to process all String fields massively.

However, if you are not constrained to use jackson, there are libraries that provide a possibility to use callbacks. For example, in Univocity parsers, ObjectRowWriterProcessor allows to achieve it in combination with multiple conversion possibilities.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=101007&siteId=1