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

How to prevent initialization of properties which are not present in JSON string during Deserialization in C#?

我给出的 class 是:

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

        public string name{ get; set; }
    }

我正在传递 json这样的字符串:

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 设置为可为 nullable int,则将再次分配默认值,即 null.

为 Newtonsoft.Josn 创建合同解析器并管理您的 serialization/deserialization。请在此处找到详细信息