YamlDotNet icon indicating copy to clipboard operation
YamlDotNet copied to clipboard

IYamlTypeConverter is ignoring tags on scalar values

Open cbenne-rl opened this issue 9 months ago • 1 comments
trafficstars

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);

}

cbenne-rl avatar Jan 29 '25 00:01 cbenne-rl