[Fixed] Could not cast or convert from System.String to System.Collections.Generic.List

Hi friends, I was working on asp.net mvc project with web api. But when I return the json from the web api and try to get in my application it throw the error while deserialize.

Could not cast or convert from System.String to System.Collections.Generic.List`1.

When I debug the code and found json auto appending /” at the start and end of the json string. I did google but didn’t found any proper solution. Then I tried my own way and it works.

Here the code.

//eg of response
// "\"[{\\\"Id\\\":1,\\\"FirstName\\\":\\\"mukesh\\\",\\\"LastName\\\":\\\"salaria\\\"}]\""

var client = new WebClient();
const string url = "http://localhost:4216/api/users";
var response = client.DownloadString(url);
response = response.TrimStart('\"');
response = response.TrimEnd('\"');
response = response.Replace("\\", "");
var result = JsonConvert.DeserializeObject<List<UserDetails>>(response);

It solved my issue and hope work for you as well.

cheers…

Posted by | View Post | View Group