我正在嘗試從我的 Api 獲取資料以將其顯示在我的 Android Xamarin 專案上。
我的 Api 具有 JWT 身份驗證。我能夠從我的 Api 獲得正確的令牌和回應,但是當我必須反序列化它時,它要么無法執行此操作,要么不會回傳任何內容。
這是無法正常作業的方法
private async Task<T> HttpGetAsync<T>(string url, string token)
{
T result = default(T);
try
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
HttpResponseMessage response = httpClient.GetAsync(url).Result;
HttpContent content = response.Content;
if (response.IsSuccessStatusCode)
{
var jsonResponse = await content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<T>(jsonResponse);
}
else
{
throw new Exception(((int)response.StatusCode).ToString() " - " response.ReasonPhrase);
}
}
catch (Exception ex)
{
one rror(ex.ToString());
}
return result;
}
所以它會像我說的那樣回傳回應
var jsonResponse = await content.ReadAsStringAsync();
但隨后它將在這一行回傳 null
result = JsonConvert.DeserializeObject<T>(jsonResponse);
如果我嘗試回傳一個串列 (JsonConvert.DeserializeObject<List>) 它將回傳這個 json 錯誤
Cannot deserialize the current JSON array (e.g. [1,2,3]) into type...
在我的代碼中,T 將是我的Category物體
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
這是我的 json
{
"data": [
{
"id": 1,
"name": "Alianzas"
},
{
"id": 2,
"name": "Pendientes"
},
{
"id": 3,
"name": "Pulseras"
},
{
"id": 4,
"name": "Colgantes"
},
{
"id": 5,
"name": "Gargantillas"
},
{
"id": 6,
"name": "Relojes"
}
],
"meta": {
"totalCount": 6,
"pageSize": 20,
"currentPage": 1,
"totalPages": 1,
"hasNextPage": false,
"hasPreviousPage": false
}
}
我在這里的錯誤是試圖用“資料”和“元”標簽反序列化 json?請幫忙。
uj5u.com熱心網友回復:
在這種情況下,你必須有一個物件應該是
public class MyObject
{
public List<Category> data { get; set; }
public Meta meta { get; set; }
}
所以你還應該有一個描述所有元屬性的 Meta 類,然后像這樣使用它
HttpGetAsync<MyObject>(url, token);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/466474.html
標籤:C# json api asp.net 核心 xamarin
