【问题标题】:Why am I getting this casting error when deserializing this json object from a Rest Service?从 Rest Service 反序列化此 json 对象时,为什么会出现此转换错误?
【发布时间】:2014-03-29 23:58:35
【问题描述】:

我正在尝试反序列化从休息服务(使用 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

我创建了以下 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;}
}

但我不断收到以下错误:

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

【问题讨论】:

    标签: json restsharp


    【解决方案1】:

    因为在 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;}
    }
    

    【讨论】:

    • 感谢克雷格。 .我收到“无参数构造函数错误”,但如果我更改为列表,它会完美运行,所以我更新了你的答案并接受
    • 我不完全确定它应该是 List 还是数组。我以为我过去使用过数组,但一定猜错了。很高兴它对你有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-04
    相关资源
    最近更新 更多