ServiceStack - 年、月和日参数描述了一个无法表示的 DateTime,即使使用 JsConfig

ServiceStack - Year, Month, and Day parameters describe an un-representable DateTime even using JsConfig

我在网上查看了多种资源,但无论我尝试什么,似乎都行不通。我做错了什么?

使用指令

using ServiceStack;
using ServiceStack.Text;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

代码

JsConfig<DateTime>.DeSerializeFn = str => DateTime.ParseExact(str, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);

using (var fs = File.Open(@"C:\temp\data.csv", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
    var data = CsvSerializer.DeserializeFromStream<List<Class>>(fs);
}

也试过

JsConfig<DateTime>.DeSerializeFn = str => DateTime.ParseExact(str, "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);
var list = File.ReadAllText(@"C:\temp\data.csv").FromCsv<List<Class>>();

csv 文件中包含什么?

开始日期、首次赎回日期、首次订阅日期

01/08/2014 00:00、31/08/2014 00:00、01/08/2014 00:00

30/09/2014 00:00、01/08/2015 00:00、30/09/2013 00:00

问题是因为您的 CSV 同时具有 , 分隔符和 </code> space 分隔符,当使用 <code>, 分隔符时 CSV 是白色的space 敏感,例如你的 Headers 应该是:

StartDate,FirstRedemptionDate,FirstSubscriptionDate

目前 'FirstRedemptionDate' 的 header 值为 ' FirstRedemptionDate'

我进行了更改,因此 header 在 this commit which allows your custom DateTime deserializer to be matched against headers with leading/trailing spaces which is available from the latest v5.7.1 that's now on MyGet 中是 auto-trimmed。

因为您的日期值也有前导白色space,您还需要在解析之前trim您的值,例如:

JsConfig<DateTime>.DeSerializeFn = str => 
    DateTime.ParseExact(str.Trim(), "dd/MM/yyyy hh:mm", CultureInfo.InvariantCulture);

现在应该使用最新的 v5.7.1 of ServiceStack.Text on MyGet.

正确解析