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

sme*_*cer 12 c# json restsharp c#-4.0

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

这是JSON响应:

{
   "Result":
   {
       "Location":
       {
           "BusinessUnit": "BTA",
           "BusinessUnitName": "CASINO",
           "LocationId": "4070",
           "LocationCode": "ZBTA",
           "LocationName": "Name of Casino"
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试代码

 [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<Location>(request);            

        //then
        Assert.IsNotNull(location.LocationId); //fails - all properties are returned null

    }
Run Code Online (Sandbox Code Playgroud)

这是我的API代码

 public T Execute<T>(RestRequest request) where T : new()
    {
        var client = new RestClient();
        client.BaseUrl = Configuration.ESBRestBaseURL;

        //request.OnBeforeDeserialization = resp => { resp.ContentLength = 761; };

        var response = client.Execute<T>(request);
        return response.Data;
    }
Run Code Online (Sandbox Code Playgroud)

最后,这是我的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; }
}
Run Code Online (Sandbox Code Playgroud)

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

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

Pet*_*ete 9

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

client.AddHandler("my_custom_type", new JsonDeserializer());
Run Code Online (Sandbox Code Playgroud)

编辑:

好的,抱歉,再次查看JSON,您需要以下内容:

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

public class LocationResult {
  public Location Location { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

然后做:

client.Execute<LocationResponse>(request);
Run Code Online (Sandbox Code Playgroud)

  • JsonDeserializer中的`RootElement`支持似乎只支持在顶层对象上指定属性作为元素,例如JSON中的"Result".它不会深入搜索对象层次结构:https://github.com/restsharp/RestSharp/blob/master/RestSharp/Deserializers/JsonDeserializer.cs (3认同)