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

IYamlTypeConverter is ignoring tags on scalar values #1037

Open
cbenne-rl opened this issue Jan 29, 2025 · 0 comments
Open

IYamlTypeConverter is ignoring tags on scalar values #1037

cbenne-rl opened this issue Jan 29, 2025 · 0 comments

Comments

@cbenne-rl
Copy link

See minimal repro below using v16.3.0. Is there a way to get this scalar to save using this tag mapping?

Expected output:

Title: YamlDocument
DoubleItem: !Double 8.500000E+000

Actual output

Title: YamlDocument
DoubleItem: 8.500000E+000

Here's the reproduction in a console app:

using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Serialization;

Console.WriteLine("Hello, World!");

var yamlDoc = new YamlDoc();
var serializer = new SerializerBuilder().WithTypeConverter(new VariableDoubleYamlConverter()).Build();

var yaml = serializer.Serialize(yamlDoc);
Console.WriteLine(yaml);

public class VariableDoubleYamlConverter : IYamlTypeConverter
{
    public bool Accepts(Type type)
    {
        return type == typeof(VariableDouble);
    }

    public object ReadYaml(IParser parser, Type type, ObjectDeserializer deserializer)
    {
        var scalar = parser.Consume<Scalar>();
        double value = 0;
        if (double.TryParse(scalar.Value, out var result))
        {
            value = result;
        }

        return value;
    }

    public void WriteYaml(IEmitter emitter, object? value, Type type, ObjectSerializer serializer)
    {
        var variableDoubleVal = (VariableDouble)(value ?? 0);
        var scalar = new Scalar(new TagName("!Double"), $"{variableDoubleVal.Value:E}");
        emitter.Emit(scalar);
    }

}

public class VariableDouble(double value)
{
    public double Value { get; set; } = value;
}

public class YamlDoc
{
    public string Title { get; set; } = "YamlDocument";
    public VariableDouble DoubleItem { get; set; } = new(8.5);

}
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