2012-06-18 125 views
9

我試圖做一個使用RestSharp的Execute方法來查詢一個剩餘端點並序列化到一個POCO的非常簡單的例子。然而,我嘗試的所有東西都會產生一個response.Data對象,它具有所有帶NULL值的屬性。當我反序列化JSON響應時,RestSharp客戶端返回所有屬性爲空

這裏是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。

這似乎是一個非常簡單的情況,但我一直在圈子裏跑來跑去!謝謝。

+0

當你調用'request.AddUrlSegment(「singleItemTestId」,singleItemTestId)'而不是你必須調用'AddParameter'時會發生什麼? –

回答

8

什麼是響應中的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); 
+0

內容類型是「application/json」。不應該是這一行:request.RootElement =「Location」;刪除您建議的「LocationResponse」對象包裝器的需求? – smercer

+0

嗯,我試過你的第二個編輯推薦它的工作後,但我不知道我明白爲什麼,除非我完全誤解了RootElement屬性的目的。非常感謝! – smercer

+3

JsonDeserializer中的'RootElement'支持似乎只支持在頂級對象上指定一個屬性作爲元素,例如,您的JSON中的「結果」。它不會深入探索對象層次結構:https://github.com/restsharp/RestSharp/blob/master/RestSharp/Deserializers/JsonDeserializer.cs – Pete

相關問題