I’m trying to deserialize my list of categories that I had on my web Api. But It won’t return anything.
First it was returning this type of error
Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {“name”:“value”}) to deserialize correctly
And I fixed it by not using await. Now on my variable jsonResponse
returns everything just fine but the variable result
is null.
Here is my code where the error is
// Generic Get Method
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)
{
OnError(ex.ToString());
}
return result;
}
And here is what my json returns
{
"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
}
}
I don’t know what is going on. Please help.
2
Answers
It works for me, though I didn’t replicate your HTTP stuff. So long as your code for that truly returns the json you posted into the
jsonResponse
string var, then I can’t see a problem:JSON receiver classes prepared by http://app.quicktype.io – no affiliation
try to use List < Category > as T class
class
or if you need Meta data, use Categories as T
classes