I have a XML that looks like this that I need to deserialize:
<?xml version="1.0" encoding="utf-8" ?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Countries>
<Country>
<CountryCode>CN</CountryCode>
<CurrentStatus>Active</CurrentStatus>
</Country>
</Countries>
<Countries>
<Country>
<CountryCode>AU</CountryCode>
<CurrentStatus>Cancelled</CurrentStatus>
</Country>
<Country>
<CountryCode>CN</CountryCode>
<CurrentStatus>Cancelled</CurrentStatus>
</Country>
<Country>
<CountryCode>US</CountryCode>
<CurrentStatus>Active</CurrentStatus>
</Country>
</Countries>
<Countries xsi:nil="true" />
</Root>
My problem here is that Countries can have Country as single and array as you can see. To get it working I have it as object
type now but it is hard to handle. What is the best solution to fix this? I'm converting it to json
since all our other systems use that and this is the only file we have that is XML.
public class Country
{
[JsonProperty("CountryCode")]
public string CountryCode { get; set; }
[JsonProperty("CurrentStatus")]
public string CurrentStatus { get; set; }
}
public class CountryInfo
{
[JsonProperty("Country")]
public object Country { get; set; }
//Does not work
//[JsonProperty("Country")]
//public IList<Country> Country { get; set; }
}
public class Root
{
[JsonProperty("Countries")]
public IList<CountryInfo> Countries { get; set; }
}
public class ExampleCountry
{
[JsonProperty("Root")]
public Root Root { get; set; }
}
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
string json = JsonConvert.SerializeXmlNode(xmlDoc);
var exampleCountries = JsonConvert.DeserializeObject<ExampleCountry>(json);
Update:
If I enable public IList<Country> Country { get; set; }
I get the following error:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.IList`1[]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.