简体   繁体   English

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

[英]RestSharp: Deserialize Xml to c# Object return null

i've an xml from some api : 我有一些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>

and mapping as object in C# class : 和映射为C#类中的对象:

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

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

I call it with this function : 我用这个函数来称呼它:

    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);
    }

but it always return null, does anyone knows why is this happening? 但是它总是返回null,有人知道为什么会这样吗?

The generic parameter passed to Execute<T> is the type that should be deserialized by the RestSharp library. 传递给Execute<T>的通用参数是应由RestSharp库反序列化的类型。 That means that your response.Data property is already of type T , which in your case is auditypes . 这意味着您的response.Data属性已经是T类型,在您的情况下是auditypes But when you return you try to cast it to a List<auditypes> where no such cast exists. 但是,当您return ,尝试将其List<auditypes>不存在此类List<auditypes>转换的List<auditypes>

Also, there is no need for the type constraint, as your method is not generic as it accepts an explicit type. 另外,不需要类型约束,因为您的方法不是通用的,因为它接受显式类型。

Refactor your method: 重构您的方法:

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;
}

Finally, it work for me :) 最后,它对我有用:)

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM