【问题标题】:Error Json deserialization and List<>错误 Json 反序列化和 List<>
【发布时间】:2014-10-10 15:00:51
【问题描述】:

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

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

要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3]) 或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,不是集合类型 像数组或列表)可以从 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&lt;Usuari.Node&gt; 是一个包含所有 JSON 消息项的数组。我尝试修复错误,但我无法找到并回答。我该如何解决?

谢谢

【问题讨论】:

    标签: c# arrays json serialization


    【解决方案1】:

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

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

    【讨论】:

    • 响应是字符串“info”,是我粘贴的第一个文本框。分析响应我认为我有一个节点数组,两个节点元素,每个元素都有不同的项目。我不明白第一种方法,如何更改服务返回?你有一个例子吗?谢谢
    • 如果你真的有一个数组,第一个字符是[。你所拥有的是一个Node Limit = 10、Offset = 0 和两个Node_sub nodes_sub 中的对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 2018-10-06
    相关资源
    最近更新 更多