2014-02-18 31 views
1

我的XML:如何反序列化xml以在RestSharp中列出?

<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>>... 

如果我改名CurrencyDataCurrency那么一切都将是这样做的权利。但我想保留这个类名。

+0

的'DeserializeAs'属性正常工作在一个单一的项目,但它并没有在收集工作。问题在于反序列化器检查用于集合的备用工作流中的'DeserializeAs'属性。我可以在'HandleListDerivative'方法中使用2-3行代码(我在Github上获取了XmlDeserializer类的源代码,并将其注册为自定义解串器,并进行了更改)。 –

回答

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以匹配套管

+0

啊,是的,别名。我的观点如下:名称必须匹配,RestSharp指南为您提供了关于如何执行查找的简要说明。 – u84six

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; 
+0

你把这个放在哪里?希望我们不必修改RestSharp库,因为我们在Xamarin中使用它... – kenyee

+0

我不确定它是否是一个疏忽。我已经离开了一些东西,所以现在我回头看看它。 – Michael

0

kay.one的答案很完美!它的工作原理与任何言论:

public List<Response> Responses { get; set; } 

工作

public Response[] Responses { get; set; } 

不`吨工作

而且

[XmlElement("AnyValue")] 

它是从System.Xml.Serialization命名空间和don`工作。 随意删除它们。 在此示例中,注释属性和属性具有相同的名称和序列化器可以理解。 但正确标注属性是从RestSharp.Deserializers命名空间

[DeserializeAs(Name="AnyXmlValue")] 
    public string AnyModelValue { get; set; } 

How to manage deserialization of RestSharp