From 056313efc821495672a9d1f7ad96741d3cf78023 Mon Sep 17 00:00:00 2001 From: xplicit Date: Tue, 7 Apr 2015 23:52:20 +0600 Subject: [PATCH] Fix number with leading zeros serialization bug JSON specification does not allow to use numbers with leading zeros see http://stackoverflow.com/questions/29048110/override-json-deserializing-a-number-with-a-leading-zero-as-a-decimal-and-not-an/29048193#29048193 for more information --- src/ServiceStack.Text/JsonObject.cs | 2 +- .../JsonTests/JsonObjectTests.cs | 21 +++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/src/ServiceStack.Text/JsonObject.cs b/src/ServiceStack.Text/JsonObject.cs index 585608ede..dac196b6e 100644 --- a/src/ServiceStack.Text/JsonObject.cs +++ b/src/ServiceStack.Text/JsonObject.cs @@ -117,7 +117,7 @@ public string Child(string key) return base[key]; } - static readonly Regex NumberRegEx = new Regex(@"^[0-9]*(?:\.[0-9]*)?$", PclExport.Instance.RegexOptions); + static readonly Regex NumberRegEx = new Regex(@"^(0|[1-9]*)(?:\.[0-9]*)?$", PclExport.Instance.RegexOptions); /// /// Write JSON Array, Object, bool or number values as raw string diff --git a/tests/ServiceStack.Text.Tests/JsonTests/JsonObjectTests.cs b/tests/ServiceStack.Text.Tests/JsonTests/JsonObjectTests.cs index 3c9970fe0..5d270f94f 100644 --- a/tests/ServiceStack.Text.Tests/JsonTests/JsonObjectTests.cs +++ b/tests/ServiceStack.Text.Tests/JsonTests/JsonObjectTests.cs @@ -26,6 +26,27 @@ public void Can_parse_empty_object_with_mixed_whitespaces() Assert.That(JsonObject.Parse("{ \n\t \n\r}"), Is.Empty); } + [Test] + public void Can_Serialize_numbers() + { + string notNumber = "{\"field\":\"00001\"}"; + Assert.AreEqual(notNumber, JsonObject.Parse(notNumber).ToJson()); + + string num1 = "{\"field\":0}"; + Assert.AreEqual(num1, JsonObject.Parse(num1).ToJson()); + + string num2 = "{\"field\":0.5}"; + Assert.AreEqual(num2, JsonObject.Parse(num2).ToJson()); + + string num3 = "{\"field\":.5}"; + Assert.AreEqual(num3, JsonObject.Parse(num3).ToJson()); + + string num4 = "{\"field\":12312}"; + Assert.AreEqual(num4, JsonObject.Parse(num4).ToJson()); + + string num5 = "{\"field\":12312.1231}"; + Assert.AreEqual(num5, JsonObject.Parse(num5).ToJson()); + } public class Jackalope {