Suppose you have this data structure that you want to write to csv (and possibly other data structures that have the same type of fields):
public class Foo
{
public Dictionary<string, string> Properties { get; set; }
public List<string> Tags { get; set; }
}
How do you make CsvHelper convert these Types to Json strings? (without writing several class maps)
[Note: I was able to piece together a solution myself, but wanted to share here]
You would write some helper method to read and write your csv, but before you call the method to read/write, you do this (tested with v23.0.0 of the nuget package):
csv.Context.TypeConverterCache.AddConverter<List<string>>(new JsonConverter<List<string>>());
csv.Context.TypeConverterCache.AddConverter<Dictionary<string,string>>(new JsonConverter<Dictionary<string,string>>());
Here's an example of the helper method for writing the records:
using (var writer = new StreamWriter(outfile, true))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.Context.TypeConverterCache.AddConverter<List<string>>(new JsonConverter<List<string>>());
csv.Context.TypeConverterCache.AddConverter<Dictionary<string,string>>(new JsonConverter<Dictionary<string,string>>());
csv.WriteRecords(yourRecords);
}
You need to add this class (which I found from the official documentation):
public class JsonConverter<T> : ITypeConverter
{
public object ConvertFromString(string text, IReaderRow row, MemberMapData memberMapData)
{
return JsonConvert.DeserializeObject<T>(text);
}
public string ConvertToString(object value, IWriterRow row, MemberMapData memberMapData)
{
return JsonConvert.SerializeObject(value);
}
}
References:
CsvHelper set default custom TypeConverter
https://joshclose.github.io/CsvHelper/examples/configuration/class-maps/type-conversion/