Asp.net-Mvc-4
使用 ReadAsAsync<T>() 反序列化複雜的 Json 對象
我想在 .net 4.0 的 mvc 項目中使用 ReadAsAsync()。結果為空。
如果我將uri輸入地址欄,chrome中的結果為(標籤名稱已更改):
<ns2:MyListResponse xmlns:ns2="blablabla"> <customerSessionId>xxcustomerSessionIdxx</customerSessionId> <numberOfRecordsRequested>0</numberOfRecordsRequested> <moreResultsAvailable>false</moreResultsAvailable> <MyList size="1" activePropertyCount="1"> <MySummary order="0"> <id>1234</id> <name>...</name> . . </MySummary> </MyList> </ns2:MyListResponse>如果我在程式碼中使用該語句:
using (var client = new HttpClient()) { var response = client.GetAsync(apiUri).Result; var message = response.Content.ReadAsStringAsync().Result; var result1 = JsonConvert.DeserializeObject<MyListResponse>(message); var result2 = response.Content.ReadAsAsync<MyListResponse>().Result; }消息以字元串格式出現
"{\"MyListResponse\":{\"customerSessionId\"...}",對應於 json 對象:{"MyListResponse": {"customerSessionId":"xxcustomerSessionIdxx", "numberOfRecordsRequested":0, "moreResultsAvailable":false, "MyList": {"@size":"1", "@activePropertyCount":"1", "MySummary": {"@order":"0", "id":1234, "name":"...", . . } } } }**result1 和 result2 的屬性為 null 或預設值。**類定義如下。我想將內容作為對象閱讀,但我不能。你有什麼建議來解決這個問題?我究竟做錯了什麼?提前致謝。
public class MySummary { public int @Order { get; set; } public string Id { get; set; } public string Name { get; set; } . . } public class MyList { public int @Size { get; set; } public int @ActivePropertyCount { get; set; } public MySummary MySummary{ get; set; } } public class MyListResponse { public string CustomerSessionId { get; set; } public int NumberOfRecordsRequested { get; set; } public bool MoreResultsAvailable { get; set; } public MyList MyList { get; set; } }
我將一個新類定義為:
public class ResponseWrapper { public MyListResponse MyListResponse { get; set; } }然後我用這個包裝器,
var result1 = JsonConvert.DeserializeObject<ResponseWrapper>(message); var result2 = response.Content.ReadAsAsync<ResponseWrapper>().Result;然後它起作用了。我只需要 MySummary 對象,但我應該編寫更多類來使其工作。
閱讀您的解決方案後,我想出了一個不需要額外課程的解決方案:
private static async Task<U> Execute<U>(HttpClient client, string path) { U output = default(U); HttpResponseMessage response = await client.GetAsync(path); if (response.IsSuccessStatusCode) { var jsonAsString = await response.Content.ReadAsStringAsync(); output = JsonConvert.DeserializeObject<U>(jsonAsString); } else { throw new ApplicationException(string.Format("Response message is not OK. Issues in action: {0}", path)); } return output; }