I know this question looks familiar but in my case, it is a bit different.
My problem, When I DeserializeObject it always returns null and I am not too sure if this is been caused by the mapping.
Question: How can I deserialize nested JSON objects for mapping the fields? Also please guide me if I have to change something in terms of converting XML to JSON
Thanks!
Converting XML response to 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 Object
{
"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# Generated class based on the JSON object
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; }
}
Simply deserialize to the root class Welcome
instead of AccountLite
.
//var des = (AccountLite)Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(AccountLite));
Welcome welcome = JsonConvert.DeserializeObject<Welcome>(json);