为什么在从Rest服务反序列化此json对象时出现此转换错误?

leo*_*ora 3 json restsharp

我试图反序列化我从休息服务(使用RestSharp)获得的json响应,但我不断收到此错误:

无法将类型为'RestSharp.JsonArray'的对象强制转换为'System.Collections.Generic.IDictionary`2 [System.String,System.Object]'.

响应如下:

“message” : “Successfully authenticated.”,
“total” : null,
“data” : [ {
  “token” : “XYZ”,
  “user” : {
    “password” : “ABC”,
    “username” : “User”
   }
}],
“success” : true
Run Code Online (Sandbox Code Playgroud)

我创建了以下C#对象:

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;}
}
Run Code Online (Sandbox Code Playgroud)

但我不断收到以下错误:

无法将类型为'RestSharp.JsonArray'的对象强制转换为'System.Collections.Generic.IDictionary`2 [System.String,System.Object]'.

Cra*_* W. 5

因为在JSON中,data值是一个数组.您需要更改AuthenticationResponse类以表示AuthenticationResponseData.

internal class AuthenticationResponse
{
    public string message { get; set; }
    public string total { get; set; }
    public List<AuthenticationResponseData> data { get; set; }
    public bool success {get;set;}
}
Run Code Online (Sandbox Code Playgroud)