【问题标题】:RestSharp not deserializingRestSharp没有反序列化
【发布时间】:2019-10-14 18:35:42
【问题描述】:

由于某种原因,RestSharp 没有反序列化响应:

RestClient client = new RestClient(baseURL);
RestRequest request = new RestRequest("api/location/" + locationID, Method.GET);
IRestResponse<Location> response = client.Execute<Location>(request);
return response.Data;

我确认 Web API 正在返回有效结果。 response 对象有:

内容:{"LocationID":3,"PrintName":"MyCountry","ISO3166_1_alpha3":"XXX"}

状态码:正常

响应状态:已完成

但是response.Data 有一个带默认值(null)的 Location 对象。

在 RestSharp Content 上使用 Json.NET 可以工作(意味着那里有正确的数据):

Location loc = JsonConvert.DeserializeObject<Location>(response.Content);

在这种情况下,Location 类应该无关紧要,因为 Json.NET 能够反序列化。由于某种原因,RestSharp 没有反序列化。

public class Location
    {
        public int LocationID;
        public string PrintName;
        public string ISO3166_1_alpha3;
    }

【问题讨论】:

  • 让我们看看你的Location 班级。
  • @CrescentFresh 没关系,因为 Json.NET 能够反序列化相同的内容。我认为 RestSharp 存在一些问题。无论如何,我会包括在内,这很简单。
  • 响应中返回的 Content-Type 标头是什么?

标签: json restsharp


【解决方案1】:

我认为 RestSharp 客户端只会反序列化属性。尝试追加

{ get; set; }

到每个字段。它应该可以工作。

【讨论】:

    【解决方案2】:

    我认为服务器返回的内容类型不正确(不是“应用程序/json”)。如果是这样,您可以通过设置正确的 Content-Type 来告诉 Restsharp 进行 json 反序列化:

    RestClient client = new RestClient(baseURL);
    RestRequest request = new RestRequest("api/location/" + locationID, Method.GET);
    
    //because the response returned is probably an incorrect content type, fix it here
    request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
    
    IRestResponse<Location> response = client.Execute<Location>(request);
    return response.Data;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多