[英]Deserialize Object returns null with nested JSON when trying to map it
我知道这个问题看起来很熟悉,但就我而言,它有点不同。
我的问题,当我 DeserializeObject 它总是返回 null 并且我不太确定这是否是由映射引起的。
问题:如何反序列化嵌套的 JSON 对象以映射字段? 如果我必须在将 XML 转换为 JSON 方面进行更改,也请指导我
谢谢!
将 XML 响应转换为 JSON
var result = await client.GetAsync($"url");
var xml = result.Content.ReadAsStringAsync().Result;
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(doc);
//the results hear is null for all the properties
var des = (AccountLite)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(AccountLite));
Console.WriteLine(des);
Console.ReadLine();
JSON 对象
{
"MessageEnvelope": {
"ListOfAccountLite": {
"AccountLite": [
{
"Id": "",
"AccountStatus": "",
"AccountTypeCode": "",
"CSN": "",
"Location": "",
"MasterAccountId": "",
"Name": ""
},
{
"Id": "",
"AccountStatus": "",
"AccountTypeCode": "",
"CSN": "",
"Location": "",
"MasterAccountId": "",
"Name": ""
},
{
"Id": "",
"AccountStatus": "",
"AccountTypeCode": "",
"CSN": "",
"Location": "",
"MasterAccountId": "",
"Name": ""
}
]
}
}
}
C#基于JSON对象生成的类
public partial class Welcome
{
[JsonProperty("MessageEnvelope")]
public MessageEnvelope MessageEnvelope { get; set; }
}
public partial class MessageEnvelope
{
[JsonProperty("ListOfAccountLite")]
public ListOfAccountLite ListOfAccountLite { get; set; }
}
public partial class ListOfAccountLite
{
[JsonProperty("AccountLite")]
public AccountLite[] AccountLite { get; set; }
}
public partial class AccountLite
{
[JsonProperty("Id")]
public string Id { get; set; }
[JsonProperty("AccountStatus")]
public string AccountStatus { get; set; }
[JsonProperty("AccountTypeCode")]
public string AccountTypeCode { get; set; }
[JsonProperty("CSN")]
public string Csn { get; set; }
[JsonProperty("Location")]
public string Location { get; set; }
[JsonProperty("MasterAccountId")]
public string MasterAccountId { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
只需反序列化为根类Welcome
而不是AccountLite
。
//var des = (AccountLite)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(AccountLite));
Welcome welcome = JsonConvert.DeserializeObject<Welcome>(json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.