aaubry / YamlDotNet

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

JsonCompatible serializer is not Json compatible #893

Open Rackover opened 5 months ago

Rackover commented 5 months ago

Describe the bug When serializing an object that contains an infinity float, the YAML DotNet serializer in JsonCompatible mode produces a JSON that contains the keyword .inf . According to JSON spec it should write null, otherwise i suppose writing a very big number or enclosing .inf with quotes would be appreciated. Currently the JSON produced by the serializer in that context is unusable for other parsers that expect valid data.

To Reproduce

 YamlDotNet.Serialization.SerializerBuilder serializerBuilder = new();
 serializerBuilder.JsonCompatible();
 serializerBuilder.WithIndentedSequences();

 var serializer = serializerBuilder.Build();

class Test
{
float a = float.PositiveInfinity;
}

var str = serializer.Serialize(a);
Console.Write(str);
EdwardCooke commented 5 months ago

Thanks for the report. It’s on my todo list. Might be a bit before I get to it. If you need it sooner go ahead and create a pr. You’ll need to handle other data types like double as well.

EdwardCooke commented 5 months ago

Can you point me to the JSON spec you're looking at for positive/negative infinity floats?

Rackover commented 5 months ago

I realize I might have made it up, it seems the real status of Infinity and NaN is unclear: https://www.ietf.org/rfc/rfc4627.txt

So it could be Null, it could be Undefined, or as someone proposed here https://stackoverflow.com/a/28763430/6230450 it could be the string "Infinity". Either choice is good I suppose as long as the final produced JSON is valid to deserialize.

Rackover commented 4 months ago
            string serialized = serializer.Serialize(heatpoint);
            Regex reg = new Regex("(\":) (\\.inf)");
            serialized = reg.Replace(serialized, "$1 0");

Currently using this as a workaround whenever i do any JSON serialization with the YAMLDotNet serializer (in case this helps anyone). I created a stub PR to hopefully make it easier for you to look into it 🙂 hope that helps !!