无法将CSV转换为Poco

时间:2017-12-02 01:16:19

标签: csv servicestack servicestack-text

我试图读取从上传表单发送的CSV文件并将其转换为我的Poco。 这是我的测试文件:

"30247685204","PWITA1","114000/2017/SE","","27/11/2017","1027/00","","","ZZPWI1","INTER MEMBER1",
"30247685205","PWITA2","114000/2017/SE","","27/11/2017","1027/00","","","ZZPWI2","INTER MEMBER2"

这是我的Poco:

public class MyOrder
{
    public string TrackingID { get; set; }
    public string CarrierName { get; set; }
    public string ConNo { get; set; }
    public string import_id { get; set; }
    public string EnteredDate { get; set; }
    public string CustomerRef { get; set; }
    public string ConDescription { get; set; }
    public string TransferAcCode { get; set; }
    public string AccountNo { get; set; }
    public string AccountName { get; set; }
}

以下是我在服务中获取文件内容的方法:

foreach (var uf in Request.Files.Where(f => f.ContentLength > 0))
{
    var content = new StreamReader(uf.InputStream).ReadToEnd();
    var orders = content.FromCsv<List<MyOrder>>();
}

如果我打破var content我可以看到我得到的文件内容如下:

"\"30247685204\",\"PWITA1\",\"114000/2017/SE\",\"\",\"27/11/2017\",\"1027/00\",\"\",\"\",\"ZZPWI1\",\"INTER MEMBER1\",\r\n\"30247685205\",\"PWITA2\",\"114000/2017/SE\",\"\",\"27/11/2017\",\"1027/00\",\"\",\"\",\"ZZPWI2\",\"INTER MEMBER2\"\r\n"

问题是我无法在var orders中获得正确的Poco订单列表。 我只得到一个元素(在文件中我有两个)并且它是空的...所有属性都设置为null! 我总是处理JSON对象,过去我没有问题,这是我第一次尝试读取CSV文件,我无法理解我错在哪里!

1 个答案:

答案 0 :(得分:2)

您可以指定不将CSV的第一行视为标题:

CsvConfig<MyOrder>.OmitHeaders = true;

最好在AppHost Configure()中设置一次静态配置,然后您可以使用以下命令对其进行反序列化:

var orders = CsvSerializer.DeserializeFromStream<List<MyOrder>>(uf.InputStream);