如何从 YAML 数组切换到映射?

How to switch from YAML array to mapping?

我正在尝试使用 YAMLDOTNET 序列化 YAML 中的自定义对象列表,结果如下:

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

你能告诉我怎样才能得到下面的结果吗?

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

我的水果清单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;
  }
}

我的水果class:

public class Fruit
{
   private int _size;

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

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

我的主要 :

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

非常感谢任何帮助。

您应该有一个 Dictionary<string, Fruit>,而不是 List<Dictionary<string, Fruit>>

现在你有一个列表,其中每个项目都是一个包含单个元素的字典,你的 YAML 输出反映了这一点。