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

Related searches

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

try
{
    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);

App.Authentication:

public static ApiResult Authentication = new ApiResult();`

JSON string:

"\"{\\"status\\":\\"0\\",\\"message\\":{\\"ID\\":5,\\"FirstName\\":\\"John\\",\\"LastName\\":\\"Doe\\",\\"Email\\":\\"testemail@gmail.com\\",\\"Password\\":\\"testPass\\",\\"CreationDate\\":\\"2016-10-26T15:01:08\\",\\"RoleID\\":1,\\"doorCode\\":9999}}\""

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 \"{\"status\":\"0\",\"message\":{\"ID\":5,\"FirstName\":\"John\",\"LastName\":\"Doe\",\"Email\":\"testemail@gmail.com\",\"Password\":\"testPass\",\"CreationDate\":\"2016-10-26T15:01:08\",\"RoleID\":1,\"doorCode\":9999}}\" to type 'App1.ApiResult'. Path '', line 1, position 232."}

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

"\"{\\"status\\":\\"0\\",\\"message\\":...

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.

Resolving “Could not cast or convert from System.String to Class , Resolving “Could not cast or convert from System.String to Class object” error. When working on API automation, I had to deserialize response� Hi..I have an issue with json serialization which throws the error: "Could not cast or convert from System.String to System.Collections.Generic.IList`1[System.String].]".

Below code worked for me along the lines of to C.Evenhuis answer,

   var content = response.Content;              
   var jsonResult = JsonConvert.DeserializeObject(content).ToString();
   var result= JsonConvert.DeserializeObject<Model>(jsonResult);

Here Content is similar to - "\"{\\"Id\\":\\"92209\\",\\"operatorId\\":100000,\\"Status\\":true, .....

Json Deserialization Error: could not cast or convert from system , "could not cast or convert from system.string to myObject". 1. 2. 3. 4. 5. 6. public class CategoryResponse public string StatusCode { get ; set ; } Also check your Json text is you property created Json object for CatRoot if its� 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.

your data model,

   var r = new ApiResult
            {
                status = "0",
                message = new Account()
                {
                    status = "0",
                    CreationDate = DateTime.Now,
                    Email = "foo@foo.com",
                    FirstName = "Trump",
                    ID = 1,
                    LastName = "Fck",
                    Password = "111",
                    RoleID = 1,
                    doorCode = 222
                }
            };


var jsonResult = Newtonsoft.Json.JsonConvert.SerializeObject(r);

var apiObject = Newtonsoft.Json.JsonConvert.DeserializeObject<ApiResult>(jsonResult);

jsonResult:

to problem look here App.client.GetUser();

[Fixed] Could not cast or convert from System.String to System , Deserialize(json); Can you help me understand the issue? I have made it a list as there can be situation to receive multiple objects and hence it is� Your Json string/object does not match any of the properties of DataDC. In order for this to work, you would at least need to have a property called name within the class. e.g.

Try using App.Authentication = JObject.Parse(request.Content.ReadAsStringAsync().Result);

Could not cast or convert from System.String to System.Type, ArgumentException: Could not cast or convert from System. String, System. EnsureTypeAssignable(Object value, Type initialType, Type� Because objects are polymorphic, it's possible for a variable of a base class type to hold a derived type. To access the derived type's instance members, it's necessary to cast the value back to the derived type. However, a cast creates the risk of throwing an InvalidCastException.

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100

@DaImTo: When you cast an object from type A to type B (if the casting) success, you will have a new object, which you can cast back to A type again. Casting is not change who they are (the core), but change what will they will be looked as. Converting, in common cases, is a one-way ticket. It make a new object (only) represent for the old object.

I will try and fix this for completionist reasons, but: changing to uniqueidentifier is the best approach; it avoids formatting concerns, malformed data, etc - and uses 16 bytes instead of 260 bytes (128 utf-16

Comments
  • jsonformatter.curiousconcept.com string r = await App.client.GetUser(); you can check "r" value here.
  • Looks like it cant parse date from your message, try to parse it without CreationDate.
  • Turns out it was serialized twice. I didn't make the API so I wasn't aware of that. Thank you.
  • In my case, my ASP.NET Core server was returning Ok(JsonConvert.SerializeObject(foo)). Changing it to Ok(foo) fixed the double-serialization issue.
  • JsonConvert.DeserializeObject<ApiResult>(JsonConvert.DeserializeObject<string>(apiResponse)). First deserialize into string and then deserialize as ApiResult model class.
  • The best answers are the simplest ones. Love you! Thank you so much!
  • On jsonResult.. I am getting Additional text encountered after finished reading JSON content error...
  • political answer