System.Text.Json serializing null becomes "null" as 'serialized' object #101420
-
Hi there, Perhaps I'm mistaken but when serialize null as in the test below, I'd expect the JsonSerializer (System.Text.Json for .NET8.0) to throw an exception of some sort, but it doesn't. What is the rationale behind this implementation, or where to find the specific documentation about this behaviour? Simple test: public class SimpleTests
{
[Fact]
public void GivenInvalidObject_WhenSerializeNull_ShouldThrowException()
{
Action act = () => JsonSerializer.Serialize<TestClass>(null);
act.Should().Throw<Exception>();
}
[Fact]
public void GivenInvalidObject_WhenSerializeNull_ShouldBeNullOrEmpty()
{
string s = JsonSerializer.Serialize<TestClass>(null);
//s = "null"
s.Should().BeNullOrEmpty();
}
} TestClass public class TestClass
{
public string Foo { get; set; }
public int Bar { get; set; }
} |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis |
Beta Was this translation helpful? Give feedback.
-
The behavior is correct.
That's why the return value of |
Beta Was this translation helpful? Give feedback.
The behavior is correct.
null
is a valid top-level JSON value. Trying in browser console you will get:That's why the return value of
JsonSerializer.Parse<T>
is always nullable, since there's top-level"null"
literal. See also #100144 (comment)