簡體   English   中英

使用 yamldotnet 反序列化 yaml 時出錯 - 找不到屬性

[英]Error deserializing yaml with yamldotnet - Property not found

我正在使用 C#、YamlDotNet 並遵循示例: 如何使用 YAMLDotNet 反序列化 YAML?

但我收到以下錯誤:

Exception thrown: 'YamlDotNet.Core.YamlException' in YamlDotNet.dll
YamlDotNet.Core.YamlException: (Line: 1, Col: 1, Idx: 0) - (Line: 1, Col: 1, Idx: 0): Exception during deserialization ---> System.Runtime.Serialization.SerializationException: Property 'PlatForm' not found on type 'NAC21_Calculator.UserSoft'.
   at YamlDotNet.Serialization.TypeInspectors.TypeInspectorSkeleton.GetProperty(Type type, Object container, String name, Boolean ignoreUnmatched)
   at YamlDotNet.Serialization.NodeDeserializers.ObjectNodeDeserializer.YamlDotNet.Serialization.INodeDeserializer.Deserialize(IParser parser, Type expectedType, Func`3 nestedObjectDeserializer, Object& value)
   at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
   --- End of inner exception stack trace ---
   at YamlDotNet.Serialization.ValueDeserializers.NodeValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
   at YamlDotNet.Serialization.ValueDeserializers.AliasValueDeserializer.DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer)
   at YamlDotNet.Serialization.Deserializer.Deserialize(IParser parser, Type type)
   at YamlDotNet.Serialization.Deserializer.Deserialize[T](IParser parser)
   at YamlDotNet.Serialization.Deserializer.Deserialize[T](TextReader input)
   at NAC21_Calculator.YamlImporter.Deserialize(String yamlName) in D:\UserInput.cs:line 124
   at NAC21_Calculator.UserInput.GenerateBut_click(Object sender, EventArgs e) in D:\UserInput.cs:line 68
The program '[20556] NAC21_Calculator.exe' has exited with code 0 (0x0).

yaml文件內容為:

PlatForm: windows
Version: 10
    # Software Info
SOFTWARE:
    Software-01:
        NAME    : MFS2020
        VERSION : 1.12.2015
        Customized  : true
    Software-02:
        NAME    : DCS
        VERSION : 6
        Customized  : false

object 定義:

public class UserSoft
    {
        public List<string> PlatForm { get; set; }
        public List<string> Version { get; set; }
        public List<software> SOFTWARE { get; set; }

        public class software
        {
            public string NAME { get; set; }
            public string VERSION { get; set; }
            public string Customized { get; set; }

        }
    }

並在按下按鈕時執行反序列化:

private void GenerateBut_click(object sender, EventArgs e)
        {
           UserSoft obj = YamlImporter.Deserialize("file_template.yml");

           Console.WriteLine("Platform: {0}", obj.PlatForm);
           Console.WriteLine("Version: {0}", obj.Version);

           foreach (var soft in obj.SOFTWARE)
                  Console.WriteLine("Software: {0}", soft);

            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }


 public class YamlImporter
    {
        public static UserSoft Deserialize(string yamlName)
        {
            StreamReader sr = new StreamReader(yamlName);
            string text = sr.ReadToEnd();
            var input = new StringReader(text);
            var deserializer = new DeserializerBuilder().WithNamingConvention(CamelCaseNamingConvention.Instance).Build();
            UserSoft deserializeObject = deserializer.Deserialize<UserSoft>(input); /* compile error */
            return deserializeObject;
        }
    }

我是 C# 的新手,這個問題是唯一真正阻礙我的問題。 提前致謝。

這里有幾個問題。

首先,您的PlatFormVersion屬性的類型是List<string> ,但值只是一個字符串。

其次,您的SOFTWARE屬性不代表一個列表,而是一個 map - 字符串“Software-01”和“Software-02”是 map 中的有效鍵。

第三,您已明確聲明要使用駝峰命名約定進行反序列化,但您的 YAML 實際上並未使用該約定。

這是一個最小的、完整的示例,其中已更正了這些方面:

using System;
using System.Collections.Generic;
using System.IO;
using YamlDotNet.Serialization;

public class UserSoft
{
    public string PlatForm { get; set; }
    public string Version { get; set; }
    public Dictionary<string, software> SOFTWARE { get; set; }

    public class software
    {
        public string NAME { get; set; }
        public string VERSION { get; set; }
        public string Customized { get; set; }

    }
}

class Program
{
    static void Main(string[] args)
    {
        string text = File.ReadAllText("test.yaml");
        var deserializer = new DeserializerBuilder().Build();
        UserSoft deserialized = deserializer.Deserialize<UserSoft>(text);
        Console.WriteLine($"Platform: {deserialized.PlatForm}");
        Console.WriteLine($"Version: {deserialized.Version}");
        foreach (var pair in deserialized.SOFTWARE)
        {
            var value = pair.Value;
            Console.WriteLine($"{pair.Key}: Name={value.NAME}; Version={value.VERSION}; Customized={value.Customized}");
        }
    }
}

Output:

Platform: windows
Version: 10
Software-01: Name=MFS2020; Version=1.12.2015; Customized=true
Software-02: Name=DCS; Version=6; Customized=false

順便說一句,我強烈建議您嘗試保持大小寫一致,並遵循 .NET 命名約定。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM