I am using ServiceStack.Text library for reading from CSV files in C#.
I would like to know how to deserialize CSV to objects where CSV contains white space separated header ?
I am using this code to deserialize CSV to empClass object:
List<empClass> objList = File.ReadAllText(filePath).FromCsv<List<empClass>>();
If I have a csv file like this
EmpId,Employee Name,Employee Address
12,JohnSmith,123 ABC Street
and my class is like
public class empClass{
public string EmpId;
public string Employee_Name;
public string Employee_Address;
}
It populates EmpId but it doesn't populate Employee Name and Employee Address as it contains the white-space in the header.
Will be grateful if anyone can help.
You can put quotes, dashes and spaces in the CSV file. Fields that contain a special character (comma, newline, or double quote), must be enclosed in double quotes.
Data saved in CSV will not retain data formatting.
CSV and spreadsheet content rules. Each row in the file must contain the same number of cells. This rule also applies to the header row. The first row must contain column headers.
The POCO class needs to match the property names of the CSV which has spaces in it, replacing it with an underscore doesn't make it match, you should also use public properties when using ServiceStack's serializers.
Since properties can't have spaces you can try using an alias, e.g:
[DataContract]
public class EmpClass
{
[DataMember]
public string EmpId { get; set; }
[DataMember(Name="Employee Name")]
public string EmployeeName { get; set; }
[DataMember(Name="Employee Address")]
public string EmployeeAddress { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With