问题
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