简体   繁体   English

配置CsvMapper以检查每个写入的值

[英]Configure CsvMapper to Inspect Each Value Written

I am using jackson-dataformat-csv to export a POJO collection to CSV as follows: 我使用jackson-dataformat-csv将POJO集合导出为CSV,如下所示:

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. 我想在将每个字段值写入CSV之前检查每个字段值,并可选择修改该值以防止Excel,表格等可能执行的公式或其他内容。 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? 如何配置CsvMapper以便为写入CSV的每个值获得回调?

Both CsvGenerator and CsvEncoder , which execute the job of processing values for CSV output, do not seem to include callback options. CsvGeneratorCsvEncoder都执行处理CSV输出值的工作,似乎不包括回调选项。 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. 不使用其他库,可以预处理pojoCollection ,目的是pojoCollection字符串字段。 Not knowing the actual structure of these pojos, the choices may be: 不知道这些pojos的实际结构,选择可能是:

  • 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. 如果pojos是紧凑的并且要处理的字段是众所周知的,则创建一个方法,该方法需要引用pojo的相应getter和setter作为args,调用getter来检索值,清理它并设置clean值。 Loop over pojoCollection to process them all. 循环遍历pojoCollection以处理它们。

  • 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. 如果字符串字段很多并且pojos具有不同类型并且它们都需要清理,则使用反射来大量处理所有String字段。

However, if you are not constrained to use jackson, there are libraries that provide a possibility to use callbacks. 但是,如果您不限制使用jackson,那么有些库可以使用回调。 For example, in Univocity parsers , ObjectRowWriterProcessor allows to achieve it in combination with multiple conversion possibilities. 例如,在Univocity解析器中ObjectRowWriterProcessor允许结合多种转换可能性来实现它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM