使用 CSVHelper 如何使用子项列表反序列化 CSV
Using CSVHelper how to deserialise an CSV with a list of Sub Item
问题:
给包含 Bar
列表的对象 FooBar
,FooBar
和 Bar
定义如下:
class FooBar{
int FooID {get;set;}
string FooProperty1 {get;set;}
List<Bar> Bars {get;set;};
}
class Bar{
int BarID {get;set;}
string BarProperty1 {get;set;}
string BarProperty2 {get;set;}
string BarProperty3 {get;set;}
}
我得到以下 CSV 作为输入:
1,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2
其中字段 BarID、BarProperty1、BarProperty2、BarProperty3 以其在集合中的索引为后缀。
如何将此输入反序列化到我的对象中?
输入范例:
1 个 FooBar 实例和 2 个子栏:1,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2
1 个 FooBar 实例但没有 Bar:
1,FooProperty1
尝试次数:
我尝试使用 Convert 将那些 属性 映射到 Bar 的新实例,例如:
public class FooBarMap : ClassMap<FooBar>
{
public FooBarMap()
{
Map(m => m.FooID);
Map(m => m.Bars).ConvertUsing(row =>
{
var list = new List<Bar>
{
new Bar {
BarProperty1 = row.GetField("BarProperty1_1"),
BarProperty2 = row.GetField("BarProperty2_1"),
// .. Other Properties
},
new Bar {}, //.. Same on _2
};
return list;
});
}
}
当然没法控制输入。我会发送 Json/Xml 而不是 CSV。
使用自定义类型转换器是可能的,但很棘手。
您需要用 Index
属性修饰 属性(即使未使用)
public class FooBar
{
[Index(2)]
public List<Bar> Bars { get; set; }
}
转换器用于读写,所以需要重写两个方法:
public class BarListConverter : DefaultTypeConverter
{
public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
{
var list = new List<Bar>();
if (text == null) return list;
do
{
var barIndex = list.Count + 1;
var bar = new Bar
{
BarID = row.GetField<int>($"BarID_{barIndex}"),
BarProperty1 = row.GetField<string>($"BarProperty1_{barIndex}"),
BarProperty2 = row.GetField<string>($"BarProperty2_{barIndex}"),
BarProperty3 = row.GetField<string>($"BarProperty3_{barIndex}")
};
list.Add(bar);
} while (row.Context.CurrentIndex > 0 && row.Context.CurrentIndex < row.Context.Record.Length - 1);
return list;
}
public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
{
var bars = value as List<Bar>;
if (bars == null) return null;
foreach (var bar in bars)
{
row.WriteField(bar.BarID);
row.WriteField(bar.BarProperty1);
row.WriteField(bar.BarProperty2);
row.WriteField(bar.BarProperty3);
}
return null;
}
}
}
阅读:
public List<FooBar> Reading()
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvReader(reader))
{
writer.WriteLine(
"FooID,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2");
writer.WriteLine("1,Foo1,1,2,3,4,5,6,7,8");
writer.Flush();
stream.Position = 0;
csv.Configuration.HeaderValidated = null;
csv.Configuration.MissingFieldFound = null;
csv.Configuration.TypeConverterCache.AddConverter<List<Bar>>(new BarListConverter());
return csv.GetRecords<FooBar>().ToList();
}
}
写作:
public string Writing(List<FooBar> data)
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvWriter(writer))
{
csv.Configuration.HasHeaderRecord = false;
csv.Configuration.TypeConverterCache.AddConverter<List<Bar>>(new BarListConverter());
csv.WriteRecords(data);
writer.Flush();
stream.Position = 0;
return reader.ReadToEnd();
}
我做了一个非常简化的方法,它将遍历 key/value 对...
private static FooBar Parse(string value)
{
// a basic check for null or empty string
if (String.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value));
// split the string
string[] split = value.Split(',');
// a basic check for properly formed key/value pairs in the string
if (split.Length < 2 || split.Length % 2 != 0)
throw new ArgumentException("Malformed string.", nameof(value));
// put the values into our object
var result = new FooBar();
// Foo pair
result.FooID = Int32.Parse(split[0]);
result.FooProperty1 = split[1];
// Bar pairs
result.Bars = new List<Bar>();
for (int i = 2; i < split.Length; i = i + 4)
{
result.Bars.Add(new Bar()
{
BarID = split[i],
BarProperty1 = split[i+1],
BarProperty2 = split[i+2],
BarProperty3 = split[i+3]
});
}
return result;
}
我运行这样对着两个例子
string value = "1,FooProperty1";
FooBar result = Parse(value); // works
和
string value = "1,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2";
FooBar result = Parse(value); // works
请注意,您的 class 需要稍微更新为
public class FooBar
{
public int FooID { get; set; }
public string FooProperty1 { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string BarID { get; set; } // you originally had this as int
public string BarProperty1 { get; set; }
public string BarProperty2 { get; set; }
public string BarProperty3 { get; set; }
}
对我来说,这个选项看起来不那么复杂,而且整体上更容易阅读。我没有特别看到您必须通过其他方式(例如使用 CSVHelper class.
强制执行转换的任何理由
问题:
给包含 Bar
列表的对象 FooBar
,FooBar
和 Bar
定义如下:
class FooBar{
int FooID {get;set;}
string FooProperty1 {get;set;}
List<Bar> Bars {get;set;};
}
class Bar{
int BarID {get;set;}
string BarProperty1 {get;set;}
string BarProperty2 {get;set;}
string BarProperty3 {get;set;}
}
我得到以下 CSV 作为输入:
1,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2
其中字段 BarID、BarProperty1、BarProperty2、BarProperty3 以其在集合中的索引为后缀。
如何将此输入反序列化到我的对象中?
输入范例:
1 个 FooBar 实例和 2 个子栏:1,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2
1 个 FooBar 实例但没有 Bar:
1,FooProperty1
尝试次数:
我尝试使用 Convert 将那些 属性 映射到 Bar 的新实例,例如:
public class FooBarMap : ClassMap<FooBar>
{
public FooBarMap()
{
Map(m => m.FooID);
Map(m => m.Bars).ConvertUsing(row =>
{
var list = new List<Bar>
{
new Bar {
BarProperty1 = row.GetField("BarProperty1_1"),
BarProperty2 = row.GetField("BarProperty2_1"),
// .. Other Properties
},
new Bar {}, //.. Same on _2
};
return list;
});
}
}
当然没法控制输入。我会发送 Json/Xml 而不是 CSV。
使用自定义类型转换器是可能的,但很棘手。
您需要用 Index
属性修饰 属性(即使未使用)
public class FooBar
{
[Index(2)]
public List<Bar> Bars { get; set; }
}
转换器用于读写,所以需要重写两个方法:
public class BarListConverter : DefaultTypeConverter
{
public override object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
{
var list = new List<Bar>();
if (text == null) return list;
do
{
var barIndex = list.Count + 1;
var bar = new Bar
{
BarID = row.GetField<int>($"BarID_{barIndex}"),
BarProperty1 = row.GetField<string>($"BarProperty1_{barIndex}"),
BarProperty2 = row.GetField<string>($"BarProperty2_{barIndex}"),
BarProperty3 = row.GetField<string>($"BarProperty3_{barIndex}")
};
list.Add(bar);
} while (row.Context.CurrentIndex > 0 && row.Context.CurrentIndex < row.Context.Record.Length - 1);
return list;
}
public override string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
{
var bars = value as List<Bar>;
if (bars == null) return null;
foreach (var bar in bars)
{
row.WriteField(bar.BarID);
row.WriteField(bar.BarProperty1);
row.WriteField(bar.BarProperty2);
row.WriteField(bar.BarProperty3);
}
return null;
}
}
}
阅读:
public List<FooBar> Reading()
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvReader(reader))
{
writer.WriteLine(
"FooID,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2");
writer.WriteLine("1,Foo1,1,2,3,4,5,6,7,8");
writer.Flush();
stream.Position = 0;
csv.Configuration.HeaderValidated = null;
csv.Configuration.MissingFieldFound = null;
csv.Configuration.TypeConverterCache.AddConverter<List<Bar>>(new BarListConverter());
return csv.GetRecords<FooBar>().ToList();
}
}
写作:
public string Writing(List<FooBar> data)
{
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))
using (var reader = new StreamReader(stream))
using (var csv = new CsvWriter(writer))
{
csv.Configuration.HasHeaderRecord = false;
csv.Configuration.TypeConverterCache.AddConverter<List<Bar>>(new BarListConverter());
csv.WriteRecords(data);
writer.Flush();
stream.Position = 0;
return reader.ReadToEnd();
}
我做了一个非常简化的方法,它将遍历 key/value 对...
private static FooBar Parse(string value)
{
// a basic check for null or empty string
if (String.IsNullOrEmpty(value)) throw new ArgumentNullException(nameof(value));
// split the string
string[] split = value.Split(',');
// a basic check for properly formed key/value pairs in the string
if (split.Length < 2 || split.Length % 2 != 0)
throw new ArgumentException("Malformed string.", nameof(value));
// put the values into our object
var result = new FooBar();
// Foo pair
result.FooID = Int32.Parse(split[0]);
result.FooProperty1 = split[1];
// Bar pairs
result.Bars = new List<Bar>();
for (int i = 2; i < split.Length; i = i + 4)
{
result.Bars.Add(new Bar()
{
BarID = split[i],
BarProperty1 = split[i+1],
BarProperty2 = split[i+2],
BarProperty3 = split[i+3]
});
}
return result;
}
我运行这样对着两个例子
string value = "1,FooProperty1";
FooBar result = Parse(value); // works
和
string value = "1,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2";
FooBar result = Parse(value); // works
请注意,您的 class 需要稍微更新为
public class FooBar
{
public int FooID { get; set; }
public string FooProperty1 { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string BarID { get; set; } // you originally had this as int
public string BarProperty1 { get; set; }
public string BarProperty2 { get; set; }
public string BarProperty3 { get; set; }
}
对我来说,这个选项看起来不那么复杂,而且整体上更容易阅读。我没有特别看到您必须通过其他方式(例如使用 CSVHelper class.
强制执行转换的任何理由