首页 > 解决方案 > JsonSerializer.Deserialize 在反序列化不同的类时预计会抛出异常

问题描述

.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; }
    }
}

我的期望是按照Microsoft 文档JsonException中的描述抛出一个。相反,我得到的是一个对象,每个属性都包含.Console.WriteLine( $"b:{b.b}" )Bnull

我错过了什么吗?

标签: c#json.net-coreserializationsystem.text.json

解决方案


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

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

编码 :

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

像这样生成json:

{ "a", "asdf" }

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

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

我希望你觉得这有帮助。


推荐阅读