繁体   English   中英

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

[英]RestSharp client returns all properties as null when deserializing JSON response

我正在尝试使用RestSharp的Execute方法查询休息端点并序列化为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<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。

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

响应中的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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM