错误Json反序列化和List<>;

本文关键字:lt gt List Json 反序列化 错误 | 更新日期: 2023-09-27 18:26:13

我正在尝试反序列化一些JSON响应。对于简单的响应我没有问题,但对于复杂的响应我得到了这个错误:

无法反序列化当前JSON对象(例如{"name":"value"})进入类型"System.Collections.Generic.List`1[APIEffilogics.Usuari+Node]",因为该类型需要一个JSON数组(例如[1,2,3])来反序列化正确地

要修复此错误,请将JSON更改为JSON数组(例如。[1,2,3])或更改反序列化的类型,使其成为正常的.NET类型(例如,不是像integer这样的基元类型,不是集合类型像数组或列表),可以从JSON对象反序列化。JsonObjectAttribute也可以添加到类型中,以强制它从JSON对象反序列化。

似乎我在反序列化字符串时放入的类型有问题。JSON字符串如下:

{
        nodes: [
          {
            id: 5,
            global_id: 5,
            description: "Oven",
            room_id: 2,
            floor_id: 1,
            building_id: 1,
            client_id: 2,
            nodemodel_id: 2,
            nodetype_id: 1
          },
          {
            id: 39,
            global_id: 39,
            description: "Fridge",
            room_id: 2,
            floor_id: 1,
            building_id: 1,
            client_id: 2,
            nodemodel_id: 8,
            nodetype_id: 1
          }, ...
        ],
        limit: 10,
        offset: 0
    }

这些是类别:

public class Node : Usuari      //Estructura nodes
{            
   [JsonProperty("limit")]
   public int limit { get; set; }
   [JsonProperty("offset")]
   public int offset { get; set; }
   [JsonProperty("nodes")]
   public List<Node_sub> nodes_sub { get; set; }
}
public class Node_sub : Node
{
    [JsonProperty("id")]
    public string nid { get; set; }
    [JsonProperty("global_id")]
    public string gid { get; set; }
    [JsonProperty("description")]
    public string descrip { get; set; }
    [JsonProperty("room_id")]
    public string rid { get; set; }
    [JsonProperty("floor_id")]
    public string fid { get; set; }
    [JsonProperty("client_id")]
    public string cid { get; set; }
    [JsonProperty("building_id")]
    public string bid { get; set; }
    [JsonProperty("nodemodel_id")]
    public string model { get; set; }
    [JsonProperty("nodetype_id")]
    public string type { get; set; }
}

代码为:

public void Request(string url, string metode, string value)
        {
            try
            {
                //Enviem la petició a la URL especificada i configurem el tipus de connexió
                HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
                myReq.KeepAlive = true;
                myReq.Headers.Set("Cache-Control", "no-store");
                myReq.Headers.Set("Pragma", "no-cache");
                myReq.Headers.Set("Authorization", usuari.token_type + " " + usuari.access_token);
                myReq.ContentType = "application/json";
                if (metode.Equals("GET") || metode.Equals("POST"))
                {
                    myReq.Method = metode;  // Set the Method property of the request to POST or GET.
                    if (body == true)
                    {
                        // add request body with chat search filters
                        List<paramet> p = new List<paramet>();
                        paramet p1 = new paramet();
                        p1.value = "1";
                        string jsonBody = JsonConvert.SerializeObject(value);
                        var requestBody = Encoding.UTF8.GetBytes(jsonBody);
                        myReq.ContentLength = requestBody.Length;
                        //myReq.ContentType = "application/json";
                        using (var stream = myReq.GetRequestStream())
                        {
                            stream.Write(requestBody, 0, requestBody.Length);   //Enviem el cos de la petició
                        }
                        body = false;
                    }
                }
                else throw new Exception("Invalid Method Type");
                //Obtenim la resposta del servidor
                HttpWebResponse myResponse = (HttpWebResponse)myReq.GetResponse();
                Stream rebut = myResponse.GetResponseStream();
                StreamReader readStream = new StreamReader(rebut, Encoding.UTF8); // Pipes the stream to a higher level stream reader with the required encoding format. 
                string info = readStream.ReadToEnd();
                if (tipus == 0) jsonclient = JsonConvert.DeserializeObject<List<Usuari.Client>>(info);
                else if (tipus == 1) jsonedif = JsonConvert.DeserializeObject<List<Usuari.Building>>(info);
                else if (tipus == 2) jsonplanta = JsonConvert.DeserializeObject<List<Usuari.Floor>>(info);
                else if (tipus == 3) jsonhab = JsonConvert.DeserializeObject<List<Usuari.Room>>(info);
                else if (tipus == 4) jsonnode = JsonConvert.DeserializeObject<List<Usuari.Node>>(info);
            }
            catch (WebException ex)
            {
                // same as normal response, get error response
                var errorResponse = (HttpWebResponse)ex.Response;
                string errorResponseJson;
                var statusCode = errorResponse.StatusCode;
                var errorIdFromHeader = errorResponse.GetResponseHeader("Error-Id");
                using (var responseStream = new StreamReader(errorResponse.GetResponseStream()))
                {
                    errorResponseJson = responseStream.ReadToEnd();
                }
                //var errorCode = JsonObject.Parse(errorResponseJson).Object("responseStatus")["errorCode"];
                //var errorMessage = JsonObject.Parse(errorResponseJson).Object("responseStatus")["message"];
            }
        }

为什么我会出现这个错误?List<Usuari.Node>是一个数组,它包含JSON消息的所有项。我试图纠正这个错误,但我找不到答案。我该怎么修?

感谢

错误Json反序列化和List<>;

服务只返回一个Node,而不是一个包含一个元素的Node数组。要解决这个问题,您可以使用以下方法之一:

  1. 更改服务,使其始终返回一个数组(通过在返回结果之前包装结果)
  2. 如果1。不是一个选项:区分客户端中的不同响应类型(检查响应是否是数组,如果不是,则告诉序列化程序解析单个Node而不是列表),然后以不同的方式处理单个对象,或者将其封装在列表中,然后像服务器那样返回一样继续