Skip to content

Serialized JSON data of some floating point values (Infinite and NaN and with exponential) contains unexpected result #991

Description

@filzrev

Describe the bug
When serialize data to JSON.
Some data are serialized as unexpected representation.

1. Serialized JSON data of floating number that contains Exponential Notation is serialized as string.
This behavior is changed by #893.
And it's required to enable JsonNumberHandling.AllowReadingFromString options to deserialize these values as float/double.
Older version of YamlDotNet serialize these data as number.

2. Serialized JSON data of Nan/PositiveInfinite/NegativeInfinite can't be deserialized with System.Text.Json
YamlDotNet serialize these values as string(.nan/.inf/-.inf).
But it's not compatible with JsonNumberHandling.AllowNamedFloatingPointLiterals options.

To Reproduce

UnitTest Code
    public class YamlJsonRoundTripTests
    {
        private static ISerializer YamlJsonSerializer = new SerializerBuilder().JsonCompatible().Build();

        private static JsonSerializerOptions CustomSerializerOptions = new JsonSerializerOptions
        {
            NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals
        };

        [Theory]
        [InlineData(1.234d, false)]
        [InlineData(double.MinValue, false)]
        [InlineData(double.MaxValue, false)]
        // Following data should be serialized to quoted JSON value.
        [InlineData(double.PositiveInfinity, true)]
        [InlineData(double.NegativeInfinity, true)]
        [InlineData(double.NaN, true)]
        public void YamlJsonRoundTripTest_SystemTextJson(object value, bool expectQuoted)
        {
            // Arrange/Act
            string json = YamlJsonSerializer.Serialize(value);
            var result = System.Text.Json.JsonSerializer.Deserialize(json, value.GetType(), CustomSerializerOptions);

            // Assert
            result.Should().BeOfType(value.GetType());
            result.Should().Be(value);

            if (expectQuoted)
            {
                json.Should().StartWith("\"")
                             .And
                             .EndWith("\"");
            }
            else
            {
                json.Should().NotStartWith("\"")
                             .And
                             .NotEndWith("\"");
            }
        }
    }

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions