Why am I getting this casting error when deserializing this json object from a Rest Service?

StackOverflow https://stackoverflow.com/questions/22733199

  •  23-06-2023
  •  | 
  •  

Question

I am trying to deserialize a json response that i am getting from a rest service (using RestSharp) but i keep getting this error:

Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.

The response looks like this:

“message” : “Successfully authenticated.”,
“total” : null,
“data” : [ {
  “token” : “XYZ”,
  “user” : {
    “password” : “ABC”,
    “username” : “User”
   }
}],
“success” : true

and I have created the following C# objects:

internal class AuthenticationResponse
{
    public string message { get; set; }
    public string total { get; set; }
    public AuthenticationResponseData data { get; set; }
    public bool success {get;set;}
}

internal class AuthenticationResponseData
{
    public string token { get; set; }
    public AuthenticationUser user {get;set;}
}

internal class AuthenticationUser
{
      public string username {get;set;}
       public string password {get;set;}
}

but i keep getting the following error:

Unable to cast object of type 'RestSharp.JsonArray' to type 'System.Collections.Generic.IDictionary`2[System.String,System.Object]'.

Était-ce utile?

La solution

Because in the JSON the data value is an array. You need to change your AuthenticationResponse class to represent AuthenticationResponseData as such.

internal class AuthenticationResponse
{
    public string message { get; set; }
    public string total { get; set; }
    public List<AuthenticationResponseData> data { get; set; }
    public bool success {get;set;}
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top