出于某种原因,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”}
StatusCode:好的
ResponseStatus:已完成
但是response.Data
有一个带有默认值(null)的Location对象。
在RestSharp内容上使用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;
}
答案 0 :(得分:0)
我认为服务器返回的内容类型不正确(不是'application / 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;
答案 1 :(得分:0)
我认为RestSharp客户端只会反序列化属性。尝试附加
{ get; set; }
每个字段。应该可以。