c# - 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}" )
B
null
我错过了什么吗?
解决方案
根据文档,如果出现以下情况,则会引发异常:
JSON 无效。
-或 -
TValue 与 JSON 不兼容。
-或 -
无法从读取器读取值。
编码 :
JsonSerializer.Serialize( new A { a = "asdf" } )
像这样生成json:
{ "a", "asdf" }
所以没有抛出异常,因为:
1 - Json 是有效的。
2 -B
与此Json兼容,就像json{}
中不存在b和c一样,因此反序列化后将为null。
3 - 读者可以阅读 Json。
例如,如果 json 类似于:""
或[]
我希望你觉得这有帮助。
推荐阅读
- python - 传入标签列表以在 for 循环中生成图形
- git - 如何在git中查找文件所有版本的总大小?
- java - 单击按钮时如何重新加载片段
- python - py3 - 在所有级别的字符串中反转标记的子字符串
- iframe - 在 IE11 上的 ms-word 插件中获取“HTTPS 安全性受到威胁”
- c++ - C++ - memcpy 给出异常:std::bad_alloc
- java - 为什么 Kubernetes 中的 Java Container 需要更多的内存作为限制?
- r - Julia中回归系数的不同标准误差
- apache-spark - 使用火花逐位比较数据框中的两列
- javascript - 在 Javascript 表单中输入扩展拉丁字符 Alt+0256-0383