1

I'm trying to serialize a list of custom objects in YAML with YAMLDOTNET and I've the following result :

fruits:
- berry:
    size: 5
- banana:
    size: 6
- coconut:
    size: 10

Could you tell me how could I have the following result ?

fruits:
 berry:
   size: 5
 banana:
   size: 6
 coconut:
   size: 10

My FruitList class :

public class FruitList
{
  private List<Dictionary<string,Fruit> _fruits;

  public List<Dictionary<string, Fruits>> fruits { get => _fruits; set => _fruits = value; }

  public FruitList(List<Dictionary<string, Fruits>> f)
  {
    fruits =f;
  }
}

My Fruit class :

public class Fruit
{
   private int _size;

   public int size { get => _size; set => _size = value; }

   public Fruit(int s)
   {
    size = s;
   }
}

My main :

List<Dictionary<string, Fruit>> list = new List<Dictionary<string, Fruit>>();
Dictionary<string, Fruit> dic = new Dictionary<string, Fruit>();
Fruit f = new Fruit(3);

dic.Add("berry",f);
list.add(dic);
FruitList fl = new FruitList(list);

var serializerBuilder = new SerializerBuilder();
var serializer = serializerBuilder.Build();
var serializer = new Serializer();
var yaml = serializer.Serialize(fl);
Console.Write(yaml);

Any help is much appreciated.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Steezix
  • 28
  • 6

1 Answers1

1

Instead of a List<Dictionary<string, Fruit>>, you should have a single Dictionary<string, Fruit>.

Right now you have a list where each item is a dictionary containing a single elements, and your YAML output reflects that.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Antoine Aubry
  • 12,203
  • 10
  • 45
  • 74