RestSharp:将Xml反序列化为c#对象返回null

时间:2014-06-11 08:02:50

标签: c# xml serialization restsharp

我是某个api的xml:

<auditypes>
     <auditype code="a" description="aaa"/>
     <auditype code="b" description="bbb"/>
     <auditype code="c" description="ccc"/>
     <auditype code="d" description="ddd"/>
     <auditype code="e" description="eee"/>
</auditypes>

并在C#类中映射为对象:

    public class auditypes
    {
        public List<auditype> auditype { get; set; }
    }

    public class auditype
    {
        public string code { get; set; }
        public string description { get; set; }
    }

我用这个函数调用它:

    public List<auditypes> Execute<auditypes>(RestRequest request) where auditypes : new()
    {
        var client = new RestClient();
        client.BaseUrl = "https://www.myurl.com/auditypes";
        var response = client.Execute<auditypes>(request);

        return response.Data as List<auditypes>;
    }

    public List<auditypes> GetCall()
    {
        var request = new RestRequest();
        request.RequestFormat = DataFormat.Xml;
        request.RootElement = "auditype";
        return Execute<auditypes>(request);
    }

但它总是返回null,有谁知道为什么会发生这种情况?

2 个答案:

答案 0 :(得分:3)

传递给Execute<T>的泛型参数是RestSharp库应该反序列化的类型。这意味着您的response.Data属性已经是T类型,在您的情况下为auditypes。但是当你return时,你会尝试将它投射到List<auditypes>,而不存在这样的演员阵容。

此外,不需要类型约束,因为您的方法不是通用的,因为它接受显式类型。

重构你的方法:

public auditypes Execute<auditypes>(RestRequest request)
{
    var client = new RestClient();
    client.BaseUrl = "https://www.myurl.com/auditypes";
    var response = client.Execute<auditypes>(request);

    return response.Data;
}

答案 1 :(得分:0)

最后,它对我有用:)

public auditypes Execute<auditypes>(RestRequest request) where auditypes : new()
{
    var client = new RestClient();
    client.BaseUrl = "https://www.myurl.com/auditypes";
    var response = client.Execute<auditypes>(request).Data;

    return response;
}

public auditypes GetCall()
{
    var request = new RestRequest();
    request.RequestFormat = DataFormat.Xml;
    return Execute<auditypes>(request);
}