Search code examples
c#.netdeserializationjson-deserializationcsvhelper

How to write object that contains arrays using csvHelper?


in C#/.net I deserialize a Api-request into a object. This object contains arrays, when i write it to file using csvHelper like this: https://joshclose.github.io/CsvHelper/examples/writing/write-class-objects/ The object is written to csv, but without the arrays.

My object which i serialize into, look like this:

public class MyMainObject
{
    public int Id { get; set; }
    public string Name { get; set; }
    public MyMissingArray[] data { get; set; }
}
public class MyMissingArray{
    public string id { get; set; }
    public string value { get; set; }
}

What is the best way to get these arrays into the csv file?


Solution

  • I think the easiest way will be to use Convert in a ClassMap. You can format the data how you want it.

    void Main()
    {
        var records = new List<MyMainObject>
        {
            new MyMainObject { 
                Id = 1, 
                Name = "Object1", 
                data = new MyMissingArray [] 
                {
                    new MyMissingArray { id = "one", value = "value1" },
                    new MyMissingArray { id = "two", value = "value2" },
                    new MyMissingArray { id = "three", value = "value3" }
                }
            }
        };
    
        using (var csv = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
        {
            csv.Context.RegisterClassMap<MyMainObjectMap>();
            csv.WriteRecords(records);
        }
    }
    
    public class MyMainObjectMap : ClassMap<MyMainObject>
    {
        public MyMainObjectMap()
        {
            Map(x => x.Id);
            Map(x => x.Name);
            Map(x => x.data).Name("MyData").Convert(args =>
            {
                var flattenMissingArray = args.Value.data.Select(d => d.id + ":" + d.value);
                return string.Join(",", flattenMissingArray);
            });
        }
    }
    
    public class MyMainObject
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public MyMissingArray[] data { get; set; }
    }
    public class MyMissingArray
    {
        public string id { get; set; }
        public string value { get; set; }
    }