From abb99e96ca3843095f81692fea0d2acbf74332cf Mon Sep 17 00:00:00 2001 From: Dylan Musil Date: Sun, 15 Jan 2023 10:22:37 -0500 Subject: [PATCH 1/2] Add test for #2775 --- Src/Newtonsoft.Json.Tests/Issues/Issue2775.cs | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Src/Newtonsoft.Json.Tests/Issues/Issue2775.cs diff --git a/Src/Newtonsoft.Json.Tests/Issues/Issue2775.cs b/Src/Newtonsoft.Json.Tests/Issues/Issue2775.cs new file mode 100644 index 000000000..5ce1bf134 --- /dev/null +++ b/Src/Newtonsoft.Json.Tests/Issues/Issue2775.cs @@ -0,0 +1,32 @@ +using System.Linq; +using Newtonsoft.Json.Linq; +#if DNXCORE50 +using Xunit; +using Test = Xunit.FactAttribute; +using Assert = Newtonsoft.Json.Tests.XUnitAssert; +using TestCase = Xunit.InlineDataAttribute; +#else +using NUnit.Framework; +#endif + +namespace Newtonsoft.Json.Tests.Issues +{ + public class Issue2775 + { + [Test] + //https://github.com/JamesNK/Newtonsoft.Json/issues/2775 + public void TokenType() + { + var jObject = new JObject { { "NullProperty", false ? "0" : null } }; + + var jToken = JToken.FromObject(jObject); + + Assert.AreEqual(JTokenType.Null, jToken.Children().Children().Single().Type); + + jObject = new JObject { { "NullProperty", (string)null } }; + + jToken = JToken.FromObject(jObject); + Assert.AreEqual(JTokenType.Null, jToken.Children().Children().Single().Type); + } + } +} \ No newline at end of file From 255e4f14832f0f0740a9e163b2db4fdcfc40b4e8 Mon Sep 17 00:00:00 2001 From: Dylan Musil Date: Sun, 15 Jan 2023 10:41:58 -0500 Subject: [PATCH 2/2] Write null when string is null --- Src/Newtonsoft.Json/Linq/JTokenWriter.cs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs index 618063e24..7092e1b7a 100644 --- a/Src/Newtonsoft.Json/Linq/JTokenWriter.cs +++ b/Src/Newtonsoft.Json/Linq/JTokenWriter.cs @@ -281,6 +281,12 @@ public override void WriteComment(string? text) /// The value to write. public override void WriteValue(string? value) { + if (value == null) + { + WriteNull(); + return; + } + base.WriteValue(value); AddJValue(new JValue(value), JsonToken.String); }