将 JSON 反序列化为 C# 对象不分配值

问题描述

我有以下 Contacts JSON 条数据 -

{
    "currentPage": 1,"totalPages": 1,"elementsOnPage": 0,"totalElements": 1,"contacts": [
        {
            "id": "9bf83fab-a485-495c-8e1f-b32c8fe9b9c6","version": 1,"type": 2
        }
    ]
}

和下面的 C# Contacts 类与 JSON 映射 -

public class Contacts
    {
       
        public System.Guid id { get; set; }

        public long version { get; set; }
      
        public ContactType type { get; set; }
    }

为了Deserialize JSON,我写了下面的代码 -

Contacts contacts = JsonConvert.DeserializeObject<Contacts>(ContactsJson);

json 只不过是上面在 Contacts JSON 中给出的 C#

现在,当我检查 contacts object 时,所有值都是 null,没有任何值分配给 object properties。我错过了什么吗?请帮助或建议。

注意 - 我不想得到 currentPagetotalPageselementsOnPagetotalElements

的值

TIA

解决方法

当你这样做时:

Contacts contacts = JsonConvert.DeserializeObject<Contacts>(ContactsJson);

DeserializeObject 期望 json 看起来像 Contacts 类的实例。如果你对那些东西不感兴趣也没关系,类的结构必须与 json 匹配。 json 是一个包含许多 联系人的对象。所以它需要匹配:

试试这个:

public class Contact
{
    public System.Guid id { get; set; }
    public long version { get; set; }
    public ContactType type { get; set; }
}

public class ContactCollection
{
    public Contact[] contacts{ get; set; }
}

然后:

var contacts = JsonConvert.DeserializeObject<ContactCollection>(ContactsJson);
,

你可以像这样声明你的类,它会反序列化。

public class Contact
{
    public Guid id { get; set; } 
    public int version { get; set; } 
    public int type { get; set; } 
}

public class Contacts
{
    public int totalElements { get; set; } 
    public List<Contact> contacts { get; set; } 
}

由于您使用的是 Newtonsoft JSON,请使用此

Contacts contacts = JsonConvert.DeserializeObject<Contacts>(ContactsJson);
,

你可以试试这个:

    JObject jObject = JObject.Parse(json);

    var contacts = jObject.SelectToken("contacts").First.ToObject<Contacts>();

假设你的类看起来像这样:

    public class Contacts
    {

        public Guid id { get; set; }

        public long version { get; set; }

        public int type { get; set; }
    }
,

您可以使用此代码:

public class Contacts
{
    public System.Guid id { get; set; }
    public long version { get; set; }
    public int type { get; set; }
}

联系人类

{{1}}

相关问答

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