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

13
我正在尝试使用RestSharp的Execute方法来查询rest端点并将其序列化为POCO的非常简单的示例。然而,我尝试的所有内容都导致响应.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<Location>(request);            

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

    }

这是我的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;
    }

最后,这是我的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。
这似乎是一个非常简单的情况,但我已经困扰了一整天!谢谢。

当您调用 request.AddUrlSegment("singleItemTestId", singleItemTestId) 而不是 AddParameter 时会发生什么? - David Hoerster
1个回答

10

响应中的Content-Type是什么?如果不是像"application/json"等标准内容类型,那么RestSharp将无法确定使用哪个反序列化器。如果实际上是一个RestSharp“不理解”的内容类型(您可以通过检查请求中发送的Accept来验证),则可以通过执行以下操作解决:

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

内容类型为“application/json”。这一行代码:request.RootElement = "Location"; 不应该消除您建议的“LocationResponse”对象包装器的需要吗? - smercer
嗯,我尝试了你的第二次编辑建议后,它起作用了,但是除非我完全误解RootElement属性的目的,否则我不确定为什么会这样。好吧,谢谢! - smercer
3
JsonDeserializer 中的 RootElement 仅支持在顶级对象中指定一个属性作为元素,例如您的 JSON 中的 "Result"。它不会深入搜索对象层次结构:https://github.com/restsharp/RestSharp/blob/master/RestSharp/Deserializers/JsonDeserializer.cs - Pete

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接