我有一個XML看起來像這樣的,我需要反序列化:C# - 處理財產,可以是單一和陣列時,XML反序列化
<?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>
我在這裏的問題是,各國可以有國家作爲單一和數組,如你所見。爲了得到它的工作,我現在把它作爲object
類型,但它很難處理。解決這個問題的最佳解決方案是什麼?我將它轉換爲json
,因爲我們所有的其他系統都使用它,這是我們唯一具有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);
更新:
如果我能public IList<Country> Country { get; set; }
我收到以下錯誤:
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.
這不是因爲你的ar ray只包含一個元素,如果它不包含元素或僅包含一個元素,則它不能爲數組。 –
爲什麼不'公共IList國家{get;組; '不行?它究竟如何不起作用? –
@AshleyPillay我假設他的意思是它並不總是能夠正常工作,因爲他可以收到一個對象(即:public Country Country {get; set;}) - 而不是一個包含單個對象的數組。 – hsoesanto