相关疑难解决方法(0)

JsonSerializer.Deserialize 的结果可以为 null 吗?

该方法的文档JsonSerializer.Deserialize中显示的返回类型均将返回类型显示为可为空。

如果您查看MS 文档中的反序列化示例,您会发现它们不一致,因为第一个和第三个将返回类型指定为可为空...

WeatherForecast? weatherForecast = 
  JsonSerializer.Deserialize<WeatherForecast>(jsonString);
Run Code Online (Sandbox Code Playgroud)

...而第二个示例缺少?,这意味着它不可为空。

通过实验,似乎只要您提供有效的 JSON(否则会出现异常),那么返回值始终是指定类型的非空对象。如果属性名称不匹配,则返回的对象将具有这些属性的默认值,但您永远不会获得空引用 - 或者至少,我找不到方法。

有谁能澄清一下吗?是否存在该方法可以返回null而不抛出异常的情况?如果不是,为什么返回类型指定为可为空?

谢谢

c# json

16
推荐指数
1
解决办法
4907
查看次数

将空文字或可能的空值转换为不可为空的类型

是否可以解决此警告:

将空文字或可能的空值转换为不可为空的类型。

不抑制此 C# 代码

 List<PropertyInfo> sourceProperties = sourceObject.GetType().GetProperties().ToList<PropertyInfo>();
            List<PropertyInfo> destinationProperties = destinationObject.GetType().GetProperties().ToList<PropertyInfo>();

            foreach (PropertyInfo sourceProperty in sourceProperties)
            {
                if (!Equals(destinationProperties, null))
                {
#pragma warning disable CS8600 // Converting null literal or possible null value to non-nullable type.
                    PropertyInfo destinationProperty = destinationProperties.Find(item => item.Name == sourceProperty.Name);
#pragma warning restore CS8600 // Converting null literal or possible null value to non-nullable type.

                   
                }
            }
Run Code Online (Sandbox Code Playgroud)

使用反射。

在此处输入图片说明

我使用的是 Visual Studio 2019 和 .NET Core 3.1。

c# .net-core

2
推荐指数
1
解决办法
2933
查看次数

标签 统计

c# ×2

.net-core ×1

json ×1