Skip to content

Commit

Permalink
Fix JsonWriter.WriteToken to allow null with string token (#2472)
Browse files Browse the repository at this point in the history
  • Loading branch information
JamesNK authored Feb 21, 2021
1 parent 926d2f0 commit 15525f1
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 4 deletions.
6 changes: 4 additions & 2 deletions Src/Newtonsoft.Json.Tests/JsonTextWriterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -945,13 +945,15 @@ public void WriteTokenDirect()
jsonWriter.WriteToken(JsonToken.StartArray);
jsonWriter.WriteToken(JsonToken.Integer, 1);
jsonWriter.WriteToken(JsonToken.StartObject);
jsonWriter.WriteToken(JsonToken.PropertyName, "string");
jsonWriter.WriteToken(JsonToken.PropertyName, "integer");
jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue);
jsonWriter.WriteToken(JsonToken.PropertyName, "null-string");
jsonWriter.WriteToken(JsonToken.String, null);
jsonWriter.WriteToken(JsonToken.EndObject);
jsonWriter.WriteToken(JsonToken.EndArray);
}

Assert.AreEqual(@"[1,{""string"":2147483647}]", sb.ToString());
Assert.AreEqual(@"[1,{""integer"":2147483647,""null-string"":null}]", sb.ToString());
}

[Test]
Expand Down
23 changes: 23 additions & 0 deletions Src/Newtonsoft.Json.Tests/Linq/JTokenWriterTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -392,5 +392,28 @@ public void DateTimeZoneHandling()

Assert.AreEqual(new DateTime(2000, 1, 1, 1, 1, 1, DateTimeKind.Utc), dt);
}

[Test]
public void WriteTokenDirect()
{
JToken token;

using (JTokenWriter jsonWriter = new JTokenWriter())
{
jsonWriter.WriteToken(JsonToken.StartArray);
jsonWriter.WriteToken(JsonToken.Integer, 1);
jsonWriter.WriteToken(JsonToken.StartObject);
jsonWriter.WriteToken(JsonToken.PropertyName, "integer");
jsonWriter.WriteToken(JsonToken.Integer, int.MaxValue);
jsonWriter.WriteToken(JsonToken.PropertyName, "null-string");
jsonWriter.WriteToken(JsonToken.String, null);
jsonWriter.WriteToken(JsonToken.EndObject);
jsonWriter.WriteToken(JsonToken.EndArray);

token = jsonWriter.Token;
}

Assert.AreEqual(@"[1,{""integer"":2147483647,""null-string"":null}]", token.ToString(Formatting.None));
}
}
}
5 changes: 3 additions & 2 deletions Src/Newtonsoft.Json/JsonWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -579,8 +579,9 @@ public void WriteToken(JsonToken token, object? value)
}
break;
case JsonToken.String:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteValue(value.ToString());
// Allow for a null string. This matches JTokenReader behavior which can read
// a JsonToken.String with a null value.
WriteValue(value?.ToString());
break;
case JsonToken.Boolean:
ValidationUtils.ArgumentNotNull(value, nameof(value));
Expand Down

0 comments on commit 15525f1

Please # to comment.