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

Sze*_*Tom 10 c# serialization json .net-core system.text.json

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

这是示例代码:

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; }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的期望是抛出一个JsonExceptionMicrosoft 文档中所述的. 我在 中得到的Console.WriteLine( $"b:{b.b}" )是一个对象B,其中每个属性都包含null

我错过了什么吗?

Moh*_*jid 6

根据文档,如果出现以下情况,则会引发异常:

JSON 无效。
- 或 -
TValue 与 JSON 不兼容。
- 或 -
无法从读取器读取值。

代码 :

JsonSerializer.Serialize( new A { a = "asdf" } )
Run Code Online (Sandbox Code Playgroud)

生成 json 如下:

{ "a", "asdf" }
Run Code Online (Sandbox Code Playgroud)

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

例如,如果 json 类似于:""[]

我希望你觉得这有帮助。