如何使用 csvHelper 编写包含数组的对象?

How to write object that contains arrays using csvHelper?

在 C#/.net 中,我将 Api 请求反序列化为一个对象。这个对象包含数组,当我像这样使用 csvHelper 将它写入文件时:https://joshclose.github.io/CsvHelper/examples/writing/write-class-objects/ 对象被写入 csv,但没有数组。

我序列化的对象如下所示:

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; }
}

将这些数组放入 csv 文件的最佳方法是什么?

我认为最简单的方法是在 ClassMap 中使用 Convert。您可以根据需要格式化 data

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; }
}