aaubry / YamlDotNet

YamlDotNet is a .NET library for YAML
MIT License
2.48k stars 466 forks source link

Using ```YamlStream``` will cause "property not found" in ```IDeserializer.Deserialize()``` #923

Closed CDboyOne closed 2 months ago

CDboyOne commented 2 months ago

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?

CDboyOne commented 2 months ago

Ok I figured it out. It was because StreamWriter inserted UTF8 BOM. I will close this.