简体   繁体   English

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

[英]JsonSerializer.Deserialize expected to throw exception when deserializing different class

In .NET Core 3.1 I use System.Text.Json.JsonSerializer to handle my Json objects..NET Core 3.1中,我使用System.Text.Json.JsonSerializer来处理我的 Json 对象。 When I tried to write an error case when the JsonSerializer.Deserialize<T>() gets a Json string that is of a different type than T I don't get any exception.当我尝试编写一个错误案例时,当JsonSerializer.Deserialize<T>()得到一个 Json 类型与T不同的字符串时,我没有得到任何异常。

Here is a sample code:这是一个示例代码:

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

My expectation would be to throw a JsonException as described in Microsoft documentation .我的期望是抛出Microsoft 文档中所述的JsonException What I get instead in the Console.WriteLine( $"b:{bb}" ) is an object of B with every property containing null .相反,我在Console.WriteLine( $"b:{bb}" )中得到的是B的 object ,每个属性都包含null

Am I missing something?我错过了什么吗?

Based on documentation, the excpetion was thrown if:根据文档,如果出现以下情况,则会抛出异常:

The JSON is invalid. JSON 无效。
-or- -要么-
TValue is not compatible with the JSON. TValue 与 JSON 不兼容。
-or- -要么-
A value could not be read from the reader.无法从读取器读取值。

The code:代码:

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

Geneate json like:生成 json,例如:

{ "a", "asdf" }

So no exception was thrown because:所以没有抛出异常,因为:
1 - The Json is valid. 1 - Json 有效。
2 - B is compatible with this Json, it's like {} , b and c are not exist in the json, so will be null after deserialization. 2 - B与此 Json 兼容,就像{}bc不存在于 json 中,因此反序列化后将是 null。
3 - The reader can read the Json. 3 - 读者可以阅读Json。

The exception will be raised if the json for example is like: "" or []例如,如果 json 类似于: ""[] ,则会引发异常

I hope you find this helpful.我希望你觉得这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM