在反序列化JSON响应时,RestSharp客户端将所有属性返回为null

我正在尝试使用RestSharp的Execute方法查询rest端点并序列化为POCO的一个非常简单的示例。 但是,我尝试的所有内容都会产生一个response.Data对象,该对象具有NULL值的所有属性。

这是JSON响应:

{ "Result": { "Location": { "BusinessUnit": "BTA", "BusinessUnitName": "CASINO", "LocationId": "4070", "LocationCode": "ZBTA", "LocationName": "Name of Casino" } } } 

这是我的测试代码

  [TestMethod] public void TestLocationsGetById() { //given var request = new RestRequest(); request.Resource = serviceEndpoint + "/{singleItemTestId}"; request.Method = Method.GET; request.AddHeader("accept", Configuration.JSONContentType); request.RootElement = "Location"; request.AddParameter("singleItemTestId", singleItemTestId, ParameterType.UrlSegment); request.RequestFormat = DataFormat.Json; //when Location location = api.Execute(request); //then Assert.IsNotNull(location.LocationId); //fails - all properties are returned null } 

这是我的API代码

  public T Execute(RestRequest request) where T : new() { var client = new RestClient(); client.BaseUrl = Configuration.ESBRestBaseURL; //request.OnBeforeDeserialization = resp => { resp.ContentLength = 761; }; var response = client.Execute(request); return response.Data; } 

最后,这是我的POCO

  public class Location { public string BusinessUnit { get; set; } public string BusinessUnitName { get; set; } public string LocationId { get; set; } public string LocationCode { get; set; } public string LocationName { get; set; } } 

此外,响应上的ErrorException和ErrorResponse属性为NULL。

这似乎是一个非常简单的案例,但我整天都在乱跑! 谢谢。

响应中的Content-Type是什么? 如果不是像“application / json”等标准内容类型,那么RestSharp将无法理解使用哪个解串器。 如果它实际上是RestSharp没有“理解”的内容类型(您可以通过检查请求中发送的Accept来validation),那么您可以通过执行以下操作来解决此问题:

 client.AddHandler("my_custom_type", new JsonDeserializer()); 

编辑:

好的,对不起,再看一下JSON,你需要这样的东西:

 public class LocationResponse public LocationResult Result { get; set; } } public class LocationResult { public Location Location { get; set; } } 

然后做:

 client.Execute(request);