JsonSerializer.Deserialize 反序列化不同 class 时预计会抛出异常

JsonSerializer.Deserialize expected to throw exception when deserializing different class

.NET Core 3.1 中,我使用 System.Text.Json.JsonSerializer 来处理我的 Json 对象。当 JsonSerializer.Deserialize<T>() 得到一个与 T 类型不同的 Json 字符串时,我试图写一个错误案例,我没有得到任何异常。

这是一个示例代码:

using System;
using System.Text.Json;

namespace JsonParsing
{
    class Program
    {
        {
            try
            {
                B b = JsonSerializer.Deserialize<B>( JsonSerializer.Serialize( new A() { a = "asdf" } ) );
                Console.WriteLine( $"b:{b.b}" );
            }
            catch( JsonException ex )
            {
                Console.WriteLine( $"Json error: {ex.Message}" );
            }
        }
    }

    public class A
    {
        public A() {}

        public string a { get; set; }
    }

    public class B
    {
        public B() {}

        public string b { get; set; }

        public C c { get; set; }
    }

    public class C
    {
        public C() {}

        public int c { get; set; }
    }
}

我的期望是抛出 JsonException,如 Microsoft documentation 中所述。我在 Console.WriteLine( $"b:{b.b}" ) 中得到的是一个 B 的对象,每个 属性 包含 null.

我是不是漏掉了什么?

根据文档,在以下情况下抛出异常:

The JSON is invalid.
-or-
TValue is not compatible with the JSON.
-or-
A value could not be read from the reader.

代码:

JsonSerializer.Serialize( new A { a = "asdf" } )

生成 json 喜欢 :

{ "a", "asdf" }

所以没有抛出异常,因为:
1 - Json 有效。
2 - B 与此 Json 兼容,就像 {}bc 不兼容存在于json中,反序列化后为null。
3 - reader 可以读取 Json.

如果 json 例如:""[]

,则会引发异常

希望对您有所帮助。