使用YamlDotNet解析Yaml文件报错“Property xxx not found”

Github地址
按照md文件,使用方法如下:

using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
...

var yml = @"
name: George Washington
age: 89
height_in_inches: 5.75
addresses:
  home:
    street: 400 Mockingbird Lane
    city: Louaryland
    state: Hawidaho
    zip: 99970
";

var deserializer = new DeserializerBuilder()
    .WithNamingConvention(UnderscoredNamingConvention.Instance)  // see height_in_inches in sample yml 
    .Build();

//yml contains a string containing your YAML
var p = deserializer.Deserialize<Person>(yml);
var h = p.Addresses["home"];
System.Console.WriteLine($"{p.Name} is {p.Age} years old and lives at {h.Street} in {h.City}, {h.State}.");

但是我按照这种方式修改为读取文件后解析一直报错“Property not found
最后发现是名称匹配方式UnderscoredNamingConvention的问题,翻译为“强调命名约定”,目前也没找到这种类型到底是什么。而我使用的驼峰命名法,应该修改为PascalCaseNamingConvention.Instance

示例配置:

ViewMapArea: 
  StartPositionX: 10
  StartPositionY: 30
  AreaWidth: 50
  AreaHeight: 80

示例代码:

private void ReadDefaultConfig()
{
    //string defaultFilePath = Path.Combine(Application.StartupPath, "MapDefaultConfig.yml");
    string defaultFilePath = Path.Combine(Application.StartupPath, "Test.yml");
    try
    {
        string input = File.ReadAllText(defaultFilePath);
        var deserializer = new DeserializerBuilder()
                      .WithNamingConvention(PascalCaseNamingConvention.Instance)
                      //.IgnoreUnmatchedProperties()   //不匹配的忽略
                      .Build();

        //读取区域信息
        Test viewMap = deserializer.Deserialize<Test>(input);
    }
    catch
    {
        throw;
    }
}

如果觉得文章对你有帮助的话,留个赞再走吧,非常感谢!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

纸照片

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值