0

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.

Kai-Rune
  • 462
  • 6
  • 17

1 Answers1

0

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
mythz
  • 141,670
  • 29
  • 246
  • 390
  • The example had a wrong separator, it should be correct now. Is CustomHeadersMap used in the deserializer? – Kai-Rune Apr 25 '16 at 22:22
  • @Kai-Rune the sample text looks like exactly the same? i.e. nothing close to CSV, I've updated my answer with an example. I've also just [added a commit](https://github.com/ServiceStack/ServiceStack.Text/commit/6085b45e63520f788d1d0b0b748cd2541e37e652) which applies these custom headers to the CSV deserializer as well. This change is now available from v4.0.57 on MyGet but you'll need to [clear your MyGet cache](https://github.com/ServiceStack/ServiceStack/wiki/MyGet#redownloading-myget-packages) to fetch the latest package versions. – mythz Apr 25 '16 at 22:40
  • I still get an error with the updated nuget package, please run the code in the question. The csv data is included in the code. – Kai-Rune Apr 26 '16 at 09:37
  • I'm also looking for this. The code example from Kai-Rune doesn't work in ServiceStack.Text 4.5.14 (installed from Nuget) @mythz – Ben Adams Sep 13 '17 at 08:06