Deserialize CSV with CustomHeaders using ServiceStack.Text

对着背影说爱祢 提交于 2019-12-12 02:54:31

问题


I'm trying to use ServiceStack.Text for deserializing a csv file containing custom headers.

var csv = "Col-1,Col-2" + Environment.NewLine +
"Val1,Val2" + Environment.NewLine +
"Val3,Val3" + Environment.NewLine;

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

ServiceStack.Text.CsvConfig<Line>.CustomHeadersMap = new Dictionary<string, string> {
    {"Col1", "Col-1"},
    {"Col2", "Col-2"}
};

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

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

CustomHeadersMap is working when SerializeToString is used. But I can't get it working when using DeserializeFromString.


回答1:


The sample text you're trying to deserialize has very little in common with the Comma-Separated Values (CSV) format that ServiceStack's CSV Format should be used to deserialize.

I'm not aware of any .NET library that can deserialize the text format in your Sample so I'd recommend running it through some a custom regex/normalizer which can convert it to a proper .csv file and deserialize that instead. Here's an example in JavaScript:

var txt = `---------------
| Col-1 | Col-2 |
---------------
| Val1 | Val2 |
---------------
| Val3 | Val4 |
---------------
`;

var csv = txt
    .replace(/^-*/mg, '')
    .replace(/(^\| | \|$)/mg, '')
    .replace(/ \| /mg,',')
    .split(/\r?\n/g)
    .filter(s => s)
    .join('\r\n') 

Where csv now contains the string:

Col-1,Col-2
Val1,Val2
Val3,Val4


来源:https://stackoverflow.com/questions/36851708/deserialize-csv-with-customheaders-using-servicestack-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!