Using CSVHelper how to deserialise an CSV with a list of Sub Item

∥☆過路亽.° 提交于 2020-08-27 18:48:47

问题


Question:

Given to object FooBar that contains a List of Bar, with FooBar and Bar define as such:

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

I get the following CSV as input:

1,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2

Where the field BarID, BarProperty1, BarProperty2, BarProperty3 are suffixed by their indice in the collection.

How do I deserialise this input into my object?


input Exemple:

1 instance of FooBar, and 2 sub Bar: 1,FooProperty1,BarID_1,BarProperty1_1,BarProperty2_1,BarProperty3_1,BarID_2,BarProperty1_2,BarProperty2_2,BarProperty3_2

1 instance of FooBar but no Bar:
1,FooProperty1


Tries:

I have try using Convert in order to map those property to a new instance of Bar like :

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

Of course no control over the input. I would have been sending Json/Xml not CSV.


回答1:


Its possible with a custom type converter but tricky.

You need to decorate the property with an Index attribute (even though it's not used)

public class FooBar
{
    [Index(2)]
    public List<Bar> Bars { get; set; }
}

The converter is used for both reading and writing, so you need to override two methods:

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

Reading:

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

Writing:

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



回答2:


I have made a very simplified method that will iterate over the key/value pairs...

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

I ran this against the two examples like so

string value = "1,FooProperty1";
FooBar result = Parse(value); // works

and

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

note that your class needs to be slightly updated to

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

To me, this option seems far less convoluted and, easier to read overall. I don't particularly see any reason that you have to force the conversion to be done via other means such as using the CSVHelper class.



来源:https://stackoverflow.com/questions/55745715/using-csvhelper-how-to-deserialise-an-csv-with-a-list-of-sub-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!