Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
CDboyOne opened this issue Apr 30, 2024 · 1 comment

Comments

@CDboyOne
Copy link

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
Copy link
Author

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant