【问题标题】:How can I add "deserialization type" function as parameter如何添加“反序列化类型”函数作为参数
【发布时间】:2021-04-22 18:17:09
【问题描述】:
string methodURL = "package/save";
object body = new { Id = userId, amount = 17, status = true };
string returnMsg = "Ok.";

public static string AddPackage(string restReq, string msg, object body){ 
    var client = new RestClient(restApiURL);
    var request = new RestRequest(restReq, Method.POST);
    request.AddHeader("Authorization", restApiUserBasicAuth);
    request.AddHeader("Content-Type", "application/json");
    request.AddJsonBody(body);
    var response = client.Execute<RootWebPackage>(request);
    
    string returnMessage = (response.Data.success) ? msg : response.Data.message;
    
    return returnMessage;
}

public class RootWebPackage {
    public bool success { get; set; } 
    public string message { get; set; } 
    public object data { get; set; } 
    public int resultCode { get; set; } 
}

AddPackage(methodURL, returnMsg, body);

我有不同的响应类,因此我需要能够动态更改此字段。如何添加“反序列化类型”函数作为参数。

【问题讨论】:

    标签: c# json rest deserialization restsharp


    【解决方案1】:

    我相信您可以执行以下操作:

    public static string AddPackage<T>(string restReq, string msg, object body){ 
      ...
      var response = client.Execute<T>(request);
    
      string returnMessage = (response.Data.success) ? msg : response.Data.message;
    
      return returnMessage;
    }
    

    这可能在语法上不正确,但我相信这可能是一种方法。

    【讨论】:

    • 那是无效的语法。应该是AddPackage&lt;T&gt;(string restReq, string msg, object body)
    • 谢谢@Aluan Haddad。即使这有点错误,因为我认为您不能通过要反序列化的对象类型的实例,而是必须通过类?
    • 你会写Execute&lt;T&gt;(...)。您传递的不是值而是类型参数
    • 好的,我明白你在说什么,谢谢!我会更新我的答案以使其更正确。
    猜你喜欢
    • 2017-11-04
    • 2016-06-08
    • 2016-09-24
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 2011-10-10
    • 2020-12-26
    • 1970-01-01
    相关资源
    最近更新 更多