csv反序列化_使用ServiceStack.Text使用CustomHeaders反序列化CSV

博客讨论了尝试使用ServiceStack.Text库解析含有自定义列名的CSV文件时遇到的问题。作者指出,提供的示例文本并不符合标准CSV格式,导致无法直接解析。解决方案建议将非标准格式转换为标准CSV,通过正则表达式进行预处理。虽然CustomHeadersMap在序列化时工作正常,但在反序列化时不起作用。提供了JavaScript示例来转换文本格式。
摘要由CSDN通过智能技术生成

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.CustomHeadersMap = new Dictionary {

{"Col1", "Col-1"},

{"Col2", "Col-2"}

};

var r2 = ServiceStack.Text.CsvSerializer.DeserializeFromString>(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.

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值