From 57025815e564d36821acf778e2c00d02225aab35 Mon Sep 17 00:00:00 2001
From: Dylan Musil <4804276+dmmusil@users.noreply.github.com>
Date: Mon, 16 Jan 2023 04:08:14 -0500
Subject: [PATCH] Fix: Null String being reported as String rather than
JTokenType.Null (#2796)
Fixes https://github.com/JamesNK/Newtonsoft.Json/issues/2775
---
Src/Newtonsoft.Json.Tests/Issues/Issue2775.cs | 32 +++++++++++++++++++
Src/Newtonsoft.Json/Linq/JTokenWriter.cs | 6 ++++
2 files changed, 38 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
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);
}