I use YamlStream to convert text to YamlDocument. After that, I will use IDeserializer to deserialize texts. However, the latter operation will throw exception as below.
Just establish a net8.0 project, reference YamlDotNet 15.1.2 and copy the following code to Program.cs:
using System.Text;
using YamlDotNet.RepresentationModel;
using YamlDotNet.Serialization;
string text = @"
Prop1: 1
";
string text2;
IDeserializer D = new DeserializerBuilder().Build();
if (true)
{
using MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text));
using StreamReader r = new(ms);
YamlStream yamlDocuments = new();
yamlDocuments.Load(r);
var doc0 = yamlDocuments.Documents[0];
yamlDocuments.Documents.Clear();
// I want to modify doc0 with some code
// and then convert it back to text.
// So I have to use YamlStream.
using MemoryStream ms2 = new();
using StreamWriter w = new(ms2, Encoding.UTF8, leaveOpen: true);
new YamlStream(doc0).Save(w, false);
w.Flush();
text2 = Encoding.UTF8.GetString(ms2.ToArray());
}
else
{
text2 = text;
}
var obj = D.Deserialize<YamlClass>(text2);
Console.WriteLine(obj);
public class YamlClass
{
public int Prop1 { get; set; }
}
This code will throw YamlDotNet.Core.YamlException saying:
'Property 'Prop1' not found on type 'YamlClass'.
However, if I change the if (true) to if (false), the exception will disappear.
Could someone please tell me the reason?
I use
YamlStream
to convert text toYamlDocument
. After that, I will useIDeserializer
to deserialize texts. However, the latter operation will throw exception as below.Just establish a
net8.0
project, referenceYamlDotNet 15.1.2
and copy the following code toProgram.cs
:This code will throw
YamlDotNet.Core.YamlException
saying:However, if I change the
if (true)
toif (false)
, the exception will disappear. Could someone please tell me the reason?