如何解决将 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
。我错过了什么吗?请帮助或建议。
注意 - 我不想得到 currentPage
、totalPages
、elementsOnPage
和 totalElements
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}}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。