如何防止在C#中反序列化期间初始化JSON字符串中不存在的属性?

问题描述

我给的班级是:

public class Myclass
    {
        public int id { get; set; }

        public string name{ get; set; }
    }

我正在像这样传递jsonString:

var jsonString = @"{ 'name': 'John'}".Replace("'","\"");

当我尝试使用以下代码反序列化上面的json字符串时:

var visitData = JsonConvert.DeserializeObject<Myclass>(jsonString,jsonSerialize);

我在visitData中得到以下值:

id : 0
name : "john"

但是我想忽略 id 属性,因为 jsonString 中不存在该属性。

我应该如何在C#中的.Net Core 3.1控制台应用程序中实现此功能。

解决方法

您可以尝试将id声明为可为空的属性

public class Myclass
{
    public int? id { get; set; } // a nullable property

    public string name{ get; set; }
}
,

通常,反序列化器将从json字符串中查找匹配属性,如果不存在,则分配默认值。在您的情况下,int的默认值为0。再次,如果将int设置为可为null的int,则将再次为该默认值赋值,即null。

对于Newtonsoft.Josn,请创建合同解析器并管理您的序列化/反序列化。请在Should not deserialize a property

中找到详细信息

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...