Asp.net

從 response.Content.ReadAsStringAsync() 獲取 c# 對象列表

  • October 10, 2021

我在 asp.net core web api 上工作,我是 asp.net core 的新手。我製作了一個 web api,並想從 web 應用程序控制器中呼叫它,它的效果很好。我的問題是我想在 c# 對象列表中轉換 json。我已經從 web api 獲得了 json 格式,但是可以將其轉換為 c# 對象列表。我用Google搜尋了很多,到處都找到了一種解決方案,那就是

 JsonConvert.DeserializeObject<BusinessUnit>(result);  

這對我不起作用。我的程式碼:

client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync(baseAddress + "/api/BusinessUnit");
var result = response.Content.ReadAsStringAsync();
List<BusinessUnit> businessunits  = JsonConvert.DeserializeObject<BusinessUnit>(result); //result shows error because it needs string as parameter.

我仍在嘗試但能夠解決這個問題。如何在 c# object list “businessunits” 中轉換 “result(json format)” ?

提前致謝。

您需要像這樣等待任務:

var result = await response.Content.ReadAsStringAsync();

使用的危險var,因為現在它推斷類型為Task<string>. 如果您嘗試過:

string result = response.Content.ReadAsStringAsync();

它會立即給您一個無法Task<string>轉換為的錯誤string

編輯:您遇到的另一個錯誤是您試圖將 JSON 反序列化為一個對象,而它實際上是一個數組。

List<BusinessUnit> businessunits = JsonConvert.DeserializeObject<List<BusinessUnit>>(result);

引用自:https://stackoverflow.com/questions/42573964