简体   繁体   English

使用 ServiceStack.Text 反序列化 CSV

[英]Deserialize CSV with ServiceStack.Text

I'm trying to use ServiceStack.Text for deserializing a csv file containing ";"我正在尝试使用 ServiceStack.Text 反序列化包含“;”的 csv 文件as the seperator.作为分隔符。

The test csv contains this data测试 csv 包含此数据

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

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

The code that works:有效的代码:

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");

The code that fails:失败的代码:

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");

When I dig into the ServiceStack code is seems like it's using the ServiceStack.Text.Common.JsWriter.ItemSeperator as a seperator for the CSV reader and not the ServiceStack.Text.CsvConfig.ItemSeperatorString.当我深入研究 ServiceStack 代码时,它似乎使用 ServiceStack.Text.Common.JsWriter.ItemSeperator 作为 CSV 阅读器的分隔符,而不是 ServiceStack.Text.CsvConfig.ItemSeperatorString。

Has anyone got this working?有没有人让这个工作?

This should now be supported from this commit .现在应该从这个 commit 中得到支持。

This change is available from v4.0.57+ that's now available from MyGet .此更改可从 v4.0.57+ 获得,现在可从 MyGet 获得

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

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