[英]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.