Skip to content

Commit

Permalink
-Change JsonValueConverter to serialize whole numbers without a decim…
Browse files Browse the repository at this point in the history
…al point
  • Loading branch information
JamesNK committed Sep 8, 2012
1 parent d9aea91 commit 39c541f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
33 changes: 33 additions & 0 deletions Src/Newtonsoft.Json.Tests/Converters/JsonValueConverterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,39 @@ public void JsonConvertSerialize()
]", json);
}

[Test]
public void SerializeDouble()
{
JsonObject o = new JsonObject();
o["zero"] = JsonValue.CreateNumberValue(0);
o["int"] = JsonValue.CreateNumberValue(1);
o["smallfraction"] = JsonValue.CreateNumberValue(3.0000000000000009);
o["double"] = JsonValue.CreateNumberValue(1.1);
o["probablyint"] = JsonValue.CreateNumberValue(1.0);
o["Epsilon"] = JsonValue.CreateNumberValue(double.Epsilon);
o["MinValue"] = JsonValue.CreateNumberValue(double.MinValue);
o["MaxValue"] = JsonValue.CreateNumberValue(double.MaxValue);
o["NaN"] = JsonValue.CreateNumberValue(double.NaN);
o["NegativeInfinity"] = JsonValue.CreateNumberValue(double.NegativeInfinity);
o["PositiveInfinity"] = JsonValue.CreateNumberValue(double.PositiveInfinity);

string json = JsonConvert.SerializeObject(o, Formatting.Indented);

Assert.AreEqual(@"{
""PositiveInfinity"": Infinity,
""NegativeInfinity"": -Infinity,
""MinValue"": -1.7976931348623157E+308,
""double"": 1.1,
""int"": 1,
""zero"": 0,
""Epsilon"": 4.94065645841247E-324,
""MaxValue"": 1.7976931348623157E+308,
""NaN"": NaN,
""smallfraction"": 3.0000000000000009,
""probablyint"": 1
}", json);
}

//[Test]
public void DeserializePerformance()
{
Expand Down
9 changes: 8 additions & 1 deletion Src/Newtonsoft.Json/Converters/JsonValueConverter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,14 @@ private void WriteJsonValue(JsonWriter writer, IJsonValue value)
break;
case JsonValueType.Number:
{
writer.WriteValue(value.GetNumber());
// JsonValue doesn't support integers
// serialize whole numbers without a decimal point
double d = value.GetNumber();
bool isInteger = (d % 1 == 0);
if (isInteger && d <= long.MaxValue && d >= long.MinValue)
writer.WriteValue(Convert.ToInt64(d));
else
writer.WriteValue(d);
}
break;
case JsonValueType.Object:
Expand Down

0 comments on commit 39c541f

Please sign in to comment.