YamlDotNet icon indicating copy to clipboard operation
YamlDotNet copied to clipboard

Serialized integral doubles/floats become strings.

Open peeveen opened this issue 4 months ago • 0 comments

If I serialize an integral double value (e.g 1.0), it becomes a string.

EDIT: From debugging, it looks like NumericRegex in JsonEventEmitter.cs is wrong. It does not match against single-digit numbers. For example, it matches 10, but not 1. Perhaps change it to something like ^-?\d+(\.\d+)?$.

EDIT2: I expect this will be fixed by this pull request. I hope it can be made official soon ... 😁

Here's my test code ...

[Fact]
public void TestNumberDeserialization() {
	var deserializer = new DeserializerBuilder()
		.WithAttemptingUnquotedStringTypeDeserialization()
		.Build();
	var yaml = string.Join('\n', "DoubleValue: 1.03", "OtherDoubleValue: 1.0", "StringValue: \"abc\"", "IntValue: 234", "BooleanValue: true");
	var yamlObject = deserializer.Deserialize(yaml);
	var serializer = new SerializerBuilder().JsonCompatible().Build();
	var json = serializer.Serialize(yamlObject);
	// At ths point, json = {"DoubleValue": 1.03, "OtherDoubleValue": "1", "StringValue": "abc", "IntValue": 234, "BooleanValue": true}
	// Why has OtherDoubleValue got quotes around it?
	// Next line fails with error about converting String to Double.
	var testObject = JsonSerializer.Deserialize<TestType>(json);
	testObject.DoubleValue.Should().Be(1.03);
	testObject.OtherDoubleValue.Should().Be(1.0);
	testObject.StringValue.Should().Be("abc");
	testObject.IntValue.Should().Be(234);
	testObject.BooleanValue.Should().BeTrue();
}

peeveen avatar Oct 16 '24 09:10 peeveen