简体   繁体   English

使用 RestSharp 反序列化为 object 和对象数组

[英]Deserializing to an object and an array of objects using RestSharp

I have an API, that either returns an object1 with Status code Ok or an array of object2 that contains error messages with Status code that is not Ok .我有一个 API,它要么返回一个带有状态码Okobject1 ,要么返回一个包含错误消息的object2数组,其中状态码不是Ok

For eg:例如:

Case of good response:反响良好的案例:

{
  "totalSize": 1,
  "done": true,
  "records": [
    {
      "Id": "some_id",
      "SomeDataField": "12345"
    }
  ]
}

My object1 model:我的对象1 object1

public class MyAPIResponse  // Blueprint for object1
{
    public int TotalSize { get; set; }
    public bool Done { get; set; }
    public List<Record> Records { get; set; }
}

public partial class Record
{    
    public string Id { get; set; }
    public string SomeDataField { get; set; }
}

Case of bad response:反应不佳的情况:

[
  {
    "message": "Session expired or invalid",
    "errorCode": "INVALID_SESSION_ID"
  },
    {
    "message": "Some other message",
    "errorCode": "SOME_OTHER_ID"
  }
]

My object2 model:我的对象2 object2

public class Errors : List<Error> { }

public class Error  // Blueprint for object2
{
    public string Message { get; set; }
    public string ErrorCode { get; set; }
}

If I try to get response now:如果我现在尝试得到回应:

public async void SendRequestAndReceiveResponse()
{
    var restClient = new RestClient("https://some.api.base.address.com");
    var request = new RestRequest("some.url", Method.GET);
    var queryBody = "some_query";
    request.AddParameter("q", queryBody , ParameterType.QueryString);
    request.AddHeader("authorization", "Bearer " + "my_access_token");
    request.AddHeader("cache-control", "no-cache");
    var response = await restClient.ExecuteAsync<MyAPIResponse>(request); // Note I'm asking it to be deserialized to object1
    // Do other stuffs with this object1 response...
}

If "good response" is coming, it's all nice and well as it gets deserialized to object1 .如果“良好的响应”即将到来,那么一切都很好,因为它被反序列化为object1

But if "bad response" is coming, then as expected I get this error because it sees array of object2 in the response but I'm telling it to deserialize to object1 :但是,如果“坏响应”即将到来,那么正如预期的那样,我会收到此错误,因为它在响应中看到object2数组,但我告诉它反序列化为object1

Unable to cast object of type 'RestSharp.JsonArray' to type 
'System.Collections.Generic.IDictionary`2[System.String,System.Object]'

So my question is:所以我的问题是:

Is there a way to create a single class (for eg: MyAPIResponse from above) that could hold both good and bad responses which would save me from doing the following to deserialize the good and bad responses?有没有办法创建一个 class (例如:上面的MyAPIResponse )可以同时保存好的和坏的响应,这将使我免于执行以下反序列化好的和坏的响应?

// Good response
var goodResponse = await restClient.ExecuteAsync<MyAPIResponse>(request);

// Bad response
var badResponse = await restClient.ExecuteAsync<Errors>(request);
//Or
var badResponse = await restClient.ExecuteAsync<List<Error>>(request);

When you use ExecuteAsync<T> or ExecuteGetAsync<T> it doesn't throw, and returns you the exception you mentioned, is that right?当您使用ExecuteAsync<T>ExecuteGetAsync<T>时,它不会抛出,而是返回您提到的异常,对吗?

You can check response.IsSuccessful and if it's false you can deserialize the response.Content to the error type manually.您可以检查response.IsSuccessful ,如果它为 false,您可以手动将response.Content反序列化为错误类型。

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

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