【问题标题】:Json.JsonSerializationException : Cannot deserialize the current JSON objectJson.JsonSerializationException : 无法反序列化当前 JSON 对象
【发布时间】:2021-12-03 00:47:51
【问题描述】:

我的问题是当我尝试反序列化我的 API json 响应时出现此错误。

Newtonsoft.Json.JsonSerializationException:'无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List`1[Entities.JsonDataType]',因为该类型需要 JSON 数组(例如 [1,2,3])正确反序列化。

我的 json 数据返回类似这样的内容

{
  "success": true,
  "result": [
    {
      "name": "USD Amerikan Doları",
      "buying": "6.6920",
      "selling": "6.6995"
    },
    {
      "name": "EUR Euro",
      "buying": "7.7322",
      "selling": "7.7393"
    },
    {
      "name": "GBP İngiliz Sterlini",
      "buying": "8.5933",
      "selling": "8.6041"
    },
    "..."
  ]
}

我的班级属性:

public class JsonDataType
    {

        //public string name { get; set; }

        //public string buying { get; set; }

        //public string selling { get; set; }

        public bool success { get; set; }
        public List<Result> result { get; set; }
    }

    public class Result
    {
        public string name { get; set; }
        public string buying { get; set; }
        public string selling { get; set; }
    } 

反序列化时出现错误:

List<JsonDataType> X = Newtonsoft.Json.JsonConvert.DeserializeObject<List<JsonDataType>>(response.Content);

我也尝试了这些代码,但都没有工作

    JsonDataType X = JsonConvert.DeserializeObject(response.Content);

IEnumerable<Result> X = (JsonDataType)JsonConvert.DeserializeObject<IEnumerable<Result>>(response.Content, typeof(JsonDataType));

List<Result> X = JsonConvert.DeserializeObject<JsonDataType>(response.Content, typeof(Result));

如果有人可以帮助我,我会很平静。 提前感谢您的时间(✿◠‿◠)

【问题讨论】:

  • 那个 JSON 不是数组/列表。如果您使用JsonConvert.DeserializeObject&lt;JsonDataType&gt;(response.Content);,它应该可以工作
  • 我已经将数据视为字符串。但我想转换为 List 类型。感谢您的评论:)
  • 我展示的代码的响应会给你一个你可以做的值foreach(var result in response.result) { ... }
  • 这就是我要找的,我终于找到了。 JsonDataType X = Newtonsoft.Json.JsonConvert.DeserializeObject(response.Content);真的非常感谢

标签: c# json .net json.net json-deserialization


【解决方案1】:

这是我的答案

JsonDataType X = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonDataType>(response.Content);

【讨论】:

  • edit您的帖子包含解释。仅代码答案没有什么长期价值
猜你喜欢
  • 1970-01-01
  • 2017-03-16
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2017-10-28
  • 1970-01-01
相关资源
最近更新 更多