2016-06-29 29 views
0

我想從我的REST API接收JSON並將其轉換爲POCO。它應該是簡單,但它真可謂是不:(Flurl:無法序列化從HttpTest收到的JSON字符串

在我的單元測試我有樣品的JSON數據串的API發送:

string mockJsonResponse = @"[{ 
       ""project_name"": ""Mailjet Support"", 
       ""cluster_name"": ""24/7 Support"", 
       ""is_billable"": ""1"", 
       ""usedtime"": ""128"" 
      }, 
      { 
       ""project_name"": ""Caring"", 
       ""cluster_name"": ""Caring"", 
       ""is_billable"": ""0"", 
       ""usedtime"": ""320"" 
      }, 
      { 
       ""project_name"": ""Engagement"", 
       ""cluster_name"": ""Community"", 
       ""is_billable"": ""0"", 
       ""usedtime"": ""8"" 
      }]"; 

我發送給我的代碼從

httpTest.RespondWithJson(mockJsonResponse); 

我想收到它在我的代碼:

dynamic response = "http://api.com".GetJsonListAsync(); 

但總是失敗,無線通過HttpTest測試TH一個非常通用的錯誤在測試資源管理器:

Result Message: Flurl.Http.FlurlHttpException : Request to http://api.com failed.

進一步深挖現在看來似乎無法序列串入POCO。我試着直接使用上面的字符串變量進行手動序列化,並且它很容易轉換爲我的模型類,所以它不可能是代碼結構問題。

// same string variable above 
var jsons = JsonConvert.DeserializeObject<List<Model>>(mockJsonResponse); // this runs fine 

所有這些失敗:

dynamic response = await "http://www.api.com".GetJsonAsync(); 
dynamic response = await "http://www.api.com".GetJsonAsync<Model>(); 
var response = await "http://www.api.com".GetJsonAsync<Model>();  
IList<dynamic> response = await "http://www.api.com".GetJsonListAsync(); 

模型類:

public class Model 
{ 
    public string project_name { get; set; } 
    public string cluster_name { get; set; } 
    public string is_billable { get; set; } 
    public string usedtime { get; set; } 
} 

編輯 我試圖得到它與GetStringAsync一個字符串,它看起來像串莫名其妙地被弄壞了。傳遞給JsonConvert.Deserialize<Model>()的字符串將無法通過測試。這是Visual Studio調試器顯示的內容。有很多轉義字符。

Screenshot of the string received from HttpTest in Visual Studio debugger

回答

1

RespondWithJson需要一個將被序列化爲JSON的對象,而不是已經序列化的字符串。用匿名對象表示測試響應,您應該很好:

var mockJsonResponse = new[] { 
    new { 
     project_name = "Mailjet Support", 
     cluster_name = "24/7 Support", 
     is_billable = "1", 
     usedtime = "128" 
    },    
    new {     
     project_name = "Caring", 
     cluster_name = "Caring", 
     is_billable = "0", 
     usedtime = "320" 
    },    
    new {    
     project_name = "Engagement", 
     cluster_name = "Community", 
     is_billable = "0", 
     usedtime = "8" 
    } 
}; 

httpTest.RespondWithJson(mockJsonResponse); 
1

在試圖手動嘲笑的JSON你是不是produsing以及格式化JSON。

我會建議創建一個集合,將其序列化並返回,作爲示例JSON。

Model[] models = new []{ 
    new Model { 
     project_name = "Mailjet Support", 
     cluster_name = "24/7 Support", 
     is_billable = "1", 
     usedtime = "128" 
    },    
    new Model{     
     project_name = "Caring", 
     cluster_name = "Caring", 
     is_billable = "0", 
     usedtime = "320" 
    },    
    new Model{    
     project_name = "Engagement", 
     cluster_name = "Community", 
     is_billable = "0", 
     usedtime = "8" 
    } 
}; 

string mockJsonResponse = Newtonsoft.Json.JsonConvert.SerializeObject(models);