我的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
,那么一切都会正确完成。但我想保留这个班级名称。
答案 0 :(得分:3)
好的,我想我明白了,
您可以尝试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以匹配套管
答案 1 :(得分:0)
然后将xml标记更改为CurrencyData。以下是有关xml反序列化器的文档:https://github.com/restsharp/RestSharp/wiki/Deserialization
答案 2 :(得分:0)
我不确定Kay.one的答案为何被接受,但它没有回答这个问题。
根据我的评论,默认的RestSharp反序列化程序在反序列化列表时不会检查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;
答案 3 :(得分:0)
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; }