Yaml 对象列表 [英] Yaml Object Lists

查看:27
本文介绍了Yaml 对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 yaml.dotnet 反序列化一个对象列表

I want to deserialize a list of objects with yaml.dotnet

你可以在下面看到我的 YAML 和源代码.

You can see my YAML and source code below.

我收到错误,即课程不是我的课程对象的一部分.因此,无论出于何种原因,编译器都希望Lesson"是类上的一个属性

I get the Error that lesson is not part of my lesson object. So for any reason the compiler is expecting that "Lesson" is a property on the class

代码:

var deserializer = new Deserializer();
var items = deserializer.Deserialize<List<YamlLesson>>(yaml);

YAML:

Lessons:
  - ShortKey: "M/A/L"
    Type: Static
    Items: ["M","A","M","L"]
  - ShortKey: "der/die/datas"
    Type: "random"
    Items: ["der","die","das"]

yaml 应该映射到的类

 public sealed class YamlLesson
    {
        public string ShortKey { get; set; }

        public string Type { get; set; }

        public List<string> Items { get; set; }
    }
}

例外:

YamlDotNet.Core.YamlException: '(Line: 1, Col: 1, Idx: 0) - (Line: 1,Col: 1, Idx: 0): 预期的 'SequenceStart',得到 'MappingStart'(在行:1,列:1,Idx:0).'

YamlDotNet.Core.YamlException: '(Line: 1, Col: 1, Idx: 0) - (Line: 1, Col: 1, Idx: 0): Expected 'SequenceStart', got 'MappingStart' (at Line: 1, Col: 1, Idx: 0).'

推荐答案

好吧,错误是你告诉 YamlDotNet 你想反序列化成一个 List,所以 YamlDotNet 期望根你的 YAML 元素是一个 sequence.但是,您的 YAML 的根元素是一个映射:它有一个键,Lessons,以及相应的值,即一系列课程.

Well, the error is that you tell YamlDotNet that you want to deserialize into a List<YamlLesson>, so YamlDotNet expects the root element of your YAML to be a sequence. However, your YAML's root element is a mapping: It has one key, Lessons, and the corresponding value, a sequence of lessons.

这个 YAML 可以正确地反序列化到这个类中:

This YAML could be properly deserialized into this class:

public class Root {
  public List<YamlLesson> Lessons { get; set; };
}

但是,如果您想直接反序列化到列表,只需删除根映射并将您的 YAML 更改为

However, if you want to deserialize directly to the List, just drop the root mapping and change your YAML to be

- ShortKey: "M/A/L"
  Type: Static
  Items: ["M","A","M","L"]
- ShortKey: "der/die/datas"
  Type: "random"
  Items: ["der","die","das"]

这篇关于Yaml 对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆