CsvHelper无法解析双列的空列

问题描述

我正在使用CsvHelper解析我的CSV文件。 在我的CSV中,我有一列包含一个双精度值,但是csv生成工具可以将其创建为空字段。

示例CSV

Name,Value,Date
Jim;1.23;20200901
John;;20200901

Jim的Value字段工作正常,但是当到达空值的John时,出现以下异常。

The conversion cannot be performed.
    Text: ''
    MemberType: System.Double
    TypeConverter: 'CsvHelper.TypeConversion.DoubleConverter'
An unexpected error occurred.

我在文档中找不到任何内容。我希望空字段认为0。

我的代码

public class Transaction
{
    public string Name { get; set; }
    public double Value { get; set; }
    public DateTime Date { get; set; }
}

在这种情况下,我像var result = ParseCsvZipArchiveEntry<Transaction>(zipArchiveEntry);

一样运行以下内容
private List<T> ParseCsvZipArchiveEntry<T>(ZipArchiveEntry zipArchiveEntry) where T : class
{
    string TempFilePath = Path.GetTempFileName();

    List<T> Result = null;

    try
    {
        zipArchiveEntry.ExtractToFile(TempFilePath,true);

        CsvHelper.Configuration.CsvConfiguration Config = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture);
        Config.Delimiter = ";";

        using (var reader = new StreamReader(TempFilePath))
        using (var csv = new CsvReader(reader,Config))
        {
            Result = csv.GetRecords<T>().ToList();
        }
    }
    catch (Exception ex)
    {
        Logger(ex.Message);
    }
    finally
    {
        if(File.Exists(TempFilePath))
            File.Delete(TempFilePath);
    }

    return Result;
}

解决方法

您可以将Default属性应用于模型中的属性。它被广告为The default value that will be used when reading when the CSV field is empty.

using CsvHelper.Configuration.Attributes;

public class Transaction
{
    public string Name { get; set; }
    [Default(0)]  // set to 0 when the field is empty
    public double Value { get; set; }
    public DateTime Date { get; set; }
}

在我的测试中,这将返回2个事务实例的列表,其中第二个实例的Value为0。

enter image description here

该属性的API文档为found here

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...