【问题标题】:How to switch from YAML array to mapping?如何从 YAML 数组切换到映射?
【发布时间】:2019-04-30 07:45:55
【问题描述】:

我正在尝试使用 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);

非常感谢任何帮助。

【问题讨论】:

  • 到目前为止你尝试了什么?
  • 我想在 yaml 中使用水果名称,所以我将数组类型从 List 更改为 List 效果很好,但现在我被困住了'-' 我不知道在哪里可以参数化。
  • 有什么代码可以分享吗?
  • 确定!我编辑了我的帖子!

标签: c# yamldotnet


【解决方案1】:

你应该有一个Dictionary&lt;string, Fruit&gt;,而不是List&lt;Dictionary&lt;string, Fruit&gt;&gt;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-08
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2023-04-01
    • 1970-01-01
    相关资源
    最近更新 更多