【问题标题】:Cannot deserialize the JSON array (e.g. [1,2,3]) into type ' ' because type requires JSON object (e.g. {"name":"value"}) to deserialize correctly无法将 JSON 数组(例如 [1,2,3])反序列化为类型 ' ',因为类型需要 JSON 对象(例如 {"name":"value"})才能正确反序列化
【发布时间】:2021-06-22 08:16:23
【问题描述】:

我有这个 JSON:

[
    {
        "Attributes": [
            {
                "Key": "Name",
                "Value": {
                    "Value": "Acc 1",
                    "Values": [
                        "Acc 1"
                    ]
                }
            },
            {
                "Key": "Id",
                "Value": {
                    "Value": "1",
                    "Values": [
                        "1"
                    ]
                }
            }
        ],
        "Name": "account",
        "Id": "1"
    },
    {
        "Attributes": [
            {
                "Key": "Name",
                "Value": {
                    "Value": "Acc 2",
                    "Values": [
                        "Acc 2"
                    ]
                }
            },
            {
                "Key": "Id",
                "Value": {
                    "Value": "2",
                    "Values": [
                        "2"
                    ]
                }
            }
        ],
        "Name": "account",
        "Id": "2"
    },
    {
        "Attributes": [
            {
                "Key": "Name",
                "Value": {
                    "Value": "Acc 3",
                    "Values": [
                        "Acc 3"
                    ]
                }
            },
            {
                "Key": "Id",
                "Value": {
                    "Value": "3",
                    "Values": [
                        "3"
                    ]
                }
            }
        ],
        "Name": "account",
        "Id": "2"
    }
]

我有这些课程:

public class RetrieveMultipleResponse
{
    public List<Attribute> Attributes { get; set; }
    public string Name { get; set; }
    public string Id { get; set; }
}

public class Value
{
    [JsonProperty("Value")]
    public string value { get; set; }
    public List<string> Values { get; set; }
}

public class Attribute
{
    public string Key { get; set; }
    public Value Value { get; set; }
}

我正在尝试使用以下代码反序列化上述 JSON:

var objResponse1 = JsonConvert.DeserializeObject<RetrieveMultipleResponse>(JsonStr);

但我收到此错误:

无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型 'test.Model.RetrieveMultipleResponse' 因为该类型需要 JSON 对象(例如 {"name":"value"})正确反序列化。要解决这个问题 错误要么将 JSON 更改为 JSON 对象(例如 {"name":"value"}) 或将反序列化类型更改为数组或实现的类型 一个集合接口(例如 ICollection、IList),比如 List 可以 从 JSON 数组反序列化。 JsonArrayAttribute 也可以 添加到类型以强制它从 JSON 数组反序列化。小路 '',第 1 行,位置 1。

【问题讨论】:

    标签: c# arrays json serialization json.net


    【解决方案1】:

    您的 json 字符串包含在方括号 ([]) 中,因此它被解释为数组而不是单个 RetrieveMultipleResponse 对象。因此,需要将其反序列化为RetrieveMultipleResponse的类型集合,例如:

    var objResponse1 = 
        JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
    

    【讨论】:

    • 我必须在“[”之前删除“//”,然后它对我有用。谢谢
    • 如果您想将其保留为单个对象而不是集合,您可以执行 JsonStr.Replace("[","").Replace("]","") 还是这不是一个好习惯吗?
    • 仅供参考,这对我不起作用,因为我从 API 获取我的 JSON,并且一整天我的 URL 都是错误的。 >
    • 这里的 RetrieveMultipleResponse 是什么?
    • 感谢这对我有用 var objResponse1 = JsonConvert.DeserializeObject>(srt); // myWord = myQuestionData.Word; Debug.Log("myWord" + objResponse1[0].Word);
    【解决方案2】:

    如果想要支持泛型(在扩展方法中),这就是模式...

    public  static List<T> Deserialize<T>(this string SerializedJSONString)
    {
        var stuff = JsonConvert.DeserializeObject<List<T>>(SerializedJSONString);
        return stuff;
    }
    

    它是这样使用的:

    var rc = new MyHttpClient(URL);
    //This response is the JSON Array (see posts above)
    var response = rc.SendRequest();
    var data = response.Deserialize<MyClassType>();
    

    MyClassType 长这样(必须匹配 JSON 数组的名称值对)

    [JsonObject(MemberSerialization = MemberSerialization.OptIn)]
     public class MyClassType
     {
        [JsonProperty(PropertyName = "Id")]
        public string Id { get; set; }
    
        [JsonProperty(PropertyName = "Name")]
        public string Name { get; set; }
    
        [JsonProperty(PropertyName = "Description")]
        public string Description { get; set; }
    
        [JsonProperty(PropertyName = "Manager")]
        public string Manager { get; set; }
    
        [JsonProperty(PropertyName = "LastUpdate")]
        public DateTime LastUpdate { get; set; }
     }
    

    使用 NUGET 下载 Newtonsoft.Json 在需要的地方添加引用...

    using Newtonsoft.Json;
    

    【讨论】:

      【解决方案3】:

      无法向解决方案添加评论,但这对我不起作用。对我有用的解决方案是使用:

      var des = (MyClass)Newtonsoft.Json.JsonConvert.DeserializeObject(response, typeof(MyClass)); 
      return des.data.Count.ToString();
      

      Deserializing JSON array into strongly typed .NET object

      【讨论】:

        【解决方案4】:

        使用这个,FrontData 是 JSON 字符串:

        var objResponse1 = JsonConvert.DeserializeObject<List<DataTransfer>>(FrontData);  
        

        并提取列表:

        var a = objResponse1[0];
        var b = a.CustomerData;
        

        【讨论】:

          【解决方案5】:

          要提取第一个元素(键),试试这个方法,其他的都是一样的:

                  using (var httpClient = new HttpClient())
                  {
                      using (var response = await httpClient.GetAsync("Your URL"))
                      {
                          var apiResponse = await response.Content.ReadAsStringAsync();
                          var list = JObject.Parse(apiResponse)["Attributes"].Select(el => new {  Key= (string)el["Key"] }).ToList();
                          var Keys= list.Select(p => p.Key).ToList();
                      }
                  }
          

          【讨论】:

            【解决方案6】:
            var objResponse1 = 
            JsonConvert.DeserializeObject<List<RetrieveMultipleResponse>>(JsonStr);
            

            成功了!

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2020-07-03
              • 1970-01-01
              相关资源
              最近更新 更多