[英]how to deserialize xml to list in RestSharp?
我的XML:
<result>
<document version="2.1.0">
<response type="currency">
<currency>
<code>AMD</code>
<price>85.1366</price>
</currency>
</response>
<response type="currency">
<currency>
<code>AUD</code>
<price>31.1207</price>
</currency>
</response>
</document>
</result>
我的課:
public class CurrencyData
{
public string Code { get; set; }
public string Price { get; set; }
}
我的解串器調用:
RestClient.ExecuteAsync<List<CurrencyData>>...
如果我改名類CurrencyData
到Currency
,然后將所有已經完成的權利。 但我想保留這個班級名稱。
好的,我想我明白了,
您可以嘗試RestClient.ExecuteAsync<Result>()
[XmlRoot("result")]
public class Result
{
[XmlElement("document")]
public Document Document { get; set; }
}
public class Document
{
[XmlElement("response")]
public Response[] Responses { get; set; }
[XmlAttribute("version")]
public string Version { get; set; }
}
public class Response
{
[XmlElement("currency")]
public CurrencyData Currency { get; set; }
[XmlAttribute("type")]
public string Type { get; set; }
}
public class CurrencyData
{
[XmlElement("code")]
public string Code { get; set; }
[XmlElement("price")]
public decimal Price { get; set; }
}
我必須添加一些XmlElement
屬性來覆蓋外殼,而不必以小寫命名類和屬性。 但是如果可以更改xml以匹配大小寫,則可以刪除它們
然后將xml標記更改為CurrencyData。 以下是有關xml反序列化器的文檔: https : //github.com/restsharp/RestSharp/wiki/Deserialization
我不確定為什么Kay.one的答案被接受,它沒有回答這個問題。
根據我的評論,默認的RestSharp反序列DeserializeAs
在反序列化列表時不檢查DeserializeAs
屬性。 我不確定這是故意的還是錯誤的,因為作者似乎並不是很有用。
無論如何,這是一個簡單的修復。
private object HandleListDerivative(object x, XElement root, string propName, Type type)
{
Type t;
if (type.IsGenericType)
{
t = type.GetGenericArguments()[0];
}
else
{
t = type.BaseType.GetGenericArguments()[0];
}
var list = (IList)Activator.CreateInstance(type);
var elements = root.Descendants(t.Name.AsNamespaced(Namespace));
var name = t.Name;
//add the following
var attribute = t.GetAttribute<DeserializeAsAttribute>();
if (attribute != null)
name = attribute.Name;
kay.one的答案是完美的! 它適用於任何評論:
public List<Response> Responses { get; set; }
作品
public Response[] Responses { get; set; }
不要工作
和
[XmlElement("AnyValue")]
它來自System.Xml.Serialization命名空間並且不起作用。 隨意刪除它們。 在此示例中,注釋屬性和屬性具有相同的名稱,並且序列化程序可以理解。 但是正確的注釋屬性來自RestSharp.Deserializers命名空間
[DeserializeAs(Name="AnyXmlValue")]
public string AnyModelValue { get; set; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.