我想從我的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調試器顯示的內容。有很多轉義字符。