java - Univocity - 如何动态提供日期格式

标签 java validation univocity

我正在尝试使用 univocity 解析器验证我的项目中的日期字段。
我知道univocity中有自定义 validator 和格式注释。但是我们需要在实现 bean 类时提供静态日期格式。

@Format(formats = "yyyy-MM-dd")
private Date createdAt
我有一个特定的要求,我需要动态提供日期格式。
这意味着我需要将日期字段解析为字符串,然后在解析 csv 文件(一种后 validator )后根据 DateTimeFormatter 验证它们。
有没有办法在运行时提供传递验证参数?
或者univocity是否支持在创建后处理所有bean的 validator ?
谢谢!

最佳答案

有可能通过将转换器设置为处理器:

import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.List;

import com.univocity.parsers.annotations.Parsed;
import com.univocity.parsers.common.processor.BeanListProcessor;
import com.univocity.parsers.conversions.Conversions;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.csv.CsvParserSettings;

public class DynamicDateFormatParser {
    public static void main(String[] args) {
        BeanListProcessor<CsvRecord> rowProcessor = new BeanListProcessor<CsvRecord>(CsvRecord.class);
        rowProcessor.convertIndexes(Conversions.toDate("dd.MM.yyyy")).set(1);

        CsvParserSettings settings = new CsvParserSettings();
        settings.setProcessor(rowProcessor);

        CsvParser parser = new CsvParser(settings);

        parser.parse(new ByteArrayInputStream("foo,31.12.2021,bar".getBytes()));

        List<CsvRecord> allRows = rowProcessor.getBeans();

        // 1 rows
        System.out.println(allRows.size() + " rows");
        
        // Fri Dec 31 00:00:00 CET 2021
        System.out.println(allRows.get(0).field2);
    }

    static class CsvRecord {
        @Parsed(index = 0)
        String field1;

        @Parsed(index = 1)
        Date field2;

        @Parsed(index = 3)
        String field3;
    }
}

关于java - Univocity - 如何动态提供日期格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66281523/

相关文章:

java - 如何从一个常见的 jar 进行日志记录

java - 在 Spring 中通过 JNDI 控制日志文件位置?

java - 配置 Http 安全

java - Log4j加载内存?

java - 使用 javax.xml.validation.Validator 针对 XSD 进行 XML 验证

java - 为什么我需要结合 BeanListProcessor 调用 parseLine 两次

javascript - 如何防止在表单中输入无效字符?

asp.net-mvc - 将带有验证器的输入控件动态添加到 View

scala - 使用Spark CSV软件包读取非常大的文件时出错

java - uniVocity - 按位置转换为列表