YamlDotNet icon indicating copy to clipboard operation
YamlDotNet copied to clipboard

JsonCompatible serializer is not Json compatible

Open Rackover opened this issue 1 year ago • 4 comments
trafficstars

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

Rackover avatar Jan 17 '24 11:01 Rackover

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 avatar Jan 22 '24 12:01 EdwardCooke

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

EdwardCooke avatar Jan 22 '24 17:01 EdwardCooke

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 avatar Jan 22 '24 19:01 Rackover

            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 !!

Rackover avatar Feb 19 '24 09:02 Rackover

This will be fixed in the next release.

EdwardCooke avatar Jul 11 '24 08:07 EdwardCooke