c#在yaml中使用列表-序列化错误



我能够对yaml文件进行反序列化,查阅和更改值。由于要求,我必须在变量NAME, VERSION,…前面使用减号(-)

文件test.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

在Johan Skeet的帮助下开发的测试程序(使用yamldotnet反序列化yaml错误-未找到属性)

我能够处理数据,但序列化不保留减号。当前代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using YamlDotNet.RepresentationModel;
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);

deserialized.PlatForm = "Linux";

Console.WriteLine("***Dumping Object Using Yaml Serializer***");
var stringBuilder = new StringBuilder();
var serializer = new Serializer();
stringBuilder.AppendLine(serializer.Serialize(deserialized));


//file construction
var stream = new FileStream("Output.yml", FileMode.OpenOrCreate);
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(stringBuilder);
writer.Close();
}
}
}

我认为这个符号与yaml文件中的List有关。所以我测试了对象的变化:

public class UserSoft
{
public string PlatForm { get; set; }
public string Version { get; set; }
public Dictionary<string, Software> SOFTWARE { get; set; }
public class Software
{
public List<string> NAME { get; set; }
public List<string> VERSION { get; set; }
public List<string> Customized { get; set; }
}
}

No success:(

Exception thrown: 'YamlDotNet.Core.YamlException' in YamlDotNet.dll
An unhandled exception of type 'YamlDotNet.Core.YamlException' occurred in YamlDotNet.dll
(Line: 5, Col: 15, Idx: 75) - (Line: 5, Col: 22, Idx: 82): Exception during deserialization

我做错了什么?

我没有发现任何可能有正确帮助的讨论。保留原始格式(包括注释)可能很好,但我在几个讨论中看到yamldotnet还不能做到这一点。这个符号是必须的。

提前感谢您,为这些基本问题感到抱歉。

你的问题在这里:

Software-01:
- NAME    : MFS2020
- VERSION : 1.12.2015
- Customized  : true

Software-01包含一个序列,其中每个项包含一个具有单个键值对的映射。要反序列化到原始结构,将其更改为

Software-01:
NAME    : MFS2020
VERSION : 1.12.2015
Customized  : true

如果要按原样反序列化YAML,请使用以下结构:

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

可以看到,由于Software-01内部有一个YAML序列,因此不能直接将其映射到自定义类。一般来说,这是可能的,但遗憾的是缺乏文档-你当然可以采用生成的UserSoft对象并手动将其转换为更好的结构。

最新更新