使用 ServiceStack.Text 反序列化 CSV

Deserialize CSV with ServiceStack.Text

我正在尝试使用 ServiceStack.Text 反序列化包含“;”的 csv 文件作为分隔符。

测试 csv 包含此数据

---------------
| Col1 | Col2 |
---------------
| Val1 | Val2 |
---------------
| Val3 | Val4 |
---------------

public class Line
{
    public string Col1 { get; set; }
    public string Col2 { get; set; }
}

有效代码:

var CsvWithComma = "Col1,Col2" + Environment.NewLine + 
"Val1,Val2" + Environment.NewLine +
"Val3,Val3" + Environment.NewLine;

var r1 = ServiceStack.Text.CsvSerializer.DeserializeFromString<List<Line>>(CsvWithComma);

Assert.That(r1.Count() == 2, "It should be 2 rows");
Assert.That(r1[0].Col1 == "Val1", "Expected Val1");
Assert.That(r1[0].Col2 == "Val2", "Expected Val2");

失败的代码:

ServiceStack.Text.CsvConfig.ItemSeperatorString = ";";

var CsvWithSemicolon = "Col1;Col2" + Environment.NewLine +
"Val1;Val2" + Environment.NewLine +
"Val3;Val3" + Environment.NewLine;

var r2 = ServiceStack.Text.CsvSerializer.DeserializeFromString<List<Line>>(CsvWithSemicolon);

Assert.That(r2.Count() == 2, "It should be 2 rows");
Assert.That(r2[0].Col1 == "Val1", "Expected Val1");
Assert.That(r2[0].Col2 == "Val2", "Expected Val2");

当我深入研究 ServiceStack 代码时,它似乎使用 ServiceStack.Text.Common.JsWriter.ItemSeperator 作为 CSV reader 的分隔符,而不是 ServiceStack.Text.CsvConfig .ItemSeperatorString。

有人成功了吗?

this commit 现在应该支持它。

此更改适用于 v4.0.57+,即现在 available from MyGet