Supahotfire420 Supahotfire420 - 1 year ago 337
C# Question

C# Could not Cast or Convert System.String to Class object

I am trying to deserialize a JSON string received from a Web API

string r = await App.client.GetUser();

App.Authentication = JsonConvert.DeserializeObject<ApiResult>(r);

await DisplayAlert("TEST", App.Authentication.ToString(), "OK");

Application.Current.MainPage = new Schedule();
catch (Exception p)
await DisplayAlert("Getting Authentication failed", p.ToString(), "TEST");

However it gives the error: Could not Cast or Convert System.String to App1.ApiResult
App.Authentication = JsonConvert.DeserializeObject<ApiResult>(r);


public static ApiResult Authentication = new ApiResult();`

JSON string:


ApiResult Class:

public class ApiResult
public string status { get; set; }
public Account message { get; set; }

Account Class:

public class Account
public string status { get; set; }
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public DateTime CreationDate { get; set; }
public int RoleID { get; set; }
public int doorCode { get; set; }

The full error message:

{"Error converting value
to type 'App1.ApiResult'. Path '', line 1, position 232."}

Answer Source

It appears that the json you receive has been serialized twice - first from ApiResult to string, then to string again:


The first double-quote might be added by your debugger, but the second (the escaped \" one) really appears to be part of the data you're processing. The error message also makes sense this way, it deserializes a string and then attempts to cast it to an ApiResult.

Try deserializing the data as a string and then deserializing its result to an ApiResult, to be sure this is the case - and if so, the server code will need to be changed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download