我正在尝试使用YAMLDOTNET序列化YAML中的自定义对象列表,并且得到以下结果:
fruits:
- berry:
size: 5
- banana:
size: 6
- coconut:
size: 10
您能告诉我如何获得以下结果吗?
fruits:
berry:
size: 5
banana:
size: 6
coconut:
size: 10
我的FruitList类:
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;
}
}
我的水果课:
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);
非常感谢您的帮助。
答案 0 :(得分:1)
您应该只有一个List<Dictionary<string, Fruit>>
,而不是Dictionary<string, Fruit>
。
现在,您有了一个列表,其中每个项目都是一个包含单个元素的字典,并且您的YAML输出反映了这一点。