[英]Can the result of JsonSerializer.Deserialize ever be null?
The return type shown in the docs for the JsonSerializer.Deserialize
method all show the return type as nullable. JsonSerializer.Deserialize
方法的文档中显示的返回类型都将返回类型显示为可为空。
If you look at the deserialisation examples in the MS docs , you see that they are inconsistent, in that the first and third specify the return type as nullable...如果您查看MS 文档中的反序列化示例,您会发现它们不一致,因为第一个和第三个将返回类型指定为可为空...
WeatherForecast? weatherForecast =
JsonSerializer.Deserialize<WeatherForecast>(jsonString);
...whereas the second example misses off the ?
...而第二个例子错过了
?
, meaning it's non-nullable. ,意味着它是不可为空的。
By experimenting, it seems that as long as you supply valid JSON (otherwise you get an exception), then the return value is always a non-null object of the specified type.通过实验,似乎只要您提供有效的 JSON(否则您会得到异常),那么返回值始终是指定类型的非空对象。 If the property names don't match, then the returned object will have default values for those properties, but you never get a null reference - or at least, I couldn't find a way.
如果属性名称不匹配,则返回的对象将具有这些属性的默认值,但您永远不会得到空引用 - 或者至少,我找不到方法。
Anyone able to clarify?任何人都可以澄清? Is there a situation in which the method can return
null
, without throwing an exception?是否存在方法可以返回
null
而不会引发异常的情况? If not, why are the return types specified as nullable?如果不是,为什么返回类型指定为可为空?
Thanks谢谢
Yes, parsing valid JSON "null"
with a JSON serializer have to return null
.是的,使用 JSON 序列化程序解析有效的 JSON
"null"
必须返回null
。
WeatherForecast? weatherForecast =
JsonSerializer.Deserialize<WeatherForecast>("null");
Note that other valid JSON strings like "123"
, "\"bob\""
, "[]"
should cause an exception because none of them represent a valid object .请注意,其他有效的 JSON字符串,如
"123"
、 "\"bob\""
、 "[]"
应该会导致异常,因为它们都不代表有效的object 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.