使用HttpWebResponse反序列化Newtonsoft JSON

4

我在所有关于Newtonsfot Json Converter反序列化的问题中进行了搜索。但是我无法在我的代码中找到问题。所以我将它放在这里,寻求帮助。

来自Visual Studio的错误消息:

No se controló Newtonsoft.Json.JsonSerializationException HResult=-2146233088 Message=无法将当前JSON数组(例如[1,2,3])反序列化为类型“APIEffilogics.Usuari+Client”,因为该类型需要一个JSON对象(例如{"name":"value"})才能正确反序列化。 要解决此错误,请将JSON更改为JSON对象(例如{"name":"value"}),或将反序列化类型更改为数组或实现集合接口的类型(例如ICollection,IList) 如列表可从JSON数组反序列化。 还可以添加JsonArrayAttribute以强制类型从JSON数组反序列化。

我的JSON响应如下:

[  {
  "id": 32,
  "consultancy_id": 1,
  "nif": "B61053922",
  "contactname": "",
  "email": "",
  "phone": "",
  "active": true,
  "description": "Keylab"   },   
{
  "id": 19,
  "consultancy_id": 1,
  "nif": "P0818300F",
  "contactname": "Pau Lloret",
  "email": "lloret@citcea.upc.edu",
  "phone": "",
  "active": true,
  "description": "Rubi"   } ]

以下是这些类:

namespace APIEffilogics
{
    public class Usuari
    {
        public string access_token;    //Encapsulat que conté la identificació de seguretat
        public string token_type;      //Tipus de token, "Bearer"
        public string response;        //Resposta de l'API

        public class Client : Usuari    //Estructura client
        {
            [JsonProperty("id")]
            public string cid { get; set; }
            [JsonProperty("consultancy_id")]
            public string consultancy_id { get; set; }
            [JsonProperty("contactname")]
            public string contactname { get; set; }
            [JsonProperty("email")]
            public string email { get; set; }
            [JsonProperty("description")]
            public string description { get; set; }
            [JsonProperty("nif")]
            public string nif { get; set; }
            [JsonProperty("phone")]
            public string phone { get; set; }
            [JsonProperty("active")]
            public string active { get; set; }
        }
        public class Building : Usuari  //Estructura edifici
        {
            public string descrip;
            public string bid;
        }
        public class Floor : Usuari     //Estructura planta
        {
            public string descrip;
            public string fid;
        }
        public class Room : Usuari      //Estructura habitació
        {
            public string descrip;
            public string rid;
        }
        public class Node : Usuari      //Estructura nodes
        {
            public string[] descrip;
            public string[] nid;
            public string[] model;
            public string[] type;
        }
    }
 //************************END PUBLIC CLASS Usuari***************************//
}

The code that I use:

public void Request(string url, string metode)
{
   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);

      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(p1);
              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);
              }
              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();
      var jsondata = JsonConvert.DeserializeObject<Usuari.Client>(info);

       myResponse.Close();
       readStream.Close();*/
    }
    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();
       }
     }
}

我不知道问题出在哪里,响应的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; }
}

代码与以前相同,只是我添加了这句话:
jsonnode = JsonConvert.DeserializeObject<List<Usuari.Node>>(info);

为什么我也遇到了同样的错误?List<Usuari.Node>是包含JSON消息中所有项目的数组。谢谢。
1个回答

3

尝试

var jsondata = JsonConvert.DeserializeObject<List<Usuari.Client>>(info);

这个问题可以从异常信息中得到提示:

要解决此错误,要么将 JSON 更改为 JSON 对象(例如 {"name":"value"}),要么将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList), 如 List 可从 JSON 数组反序列化

强调重点以突出要点

你收到的HTTP响应是一个对象数组,因此您需要以可以处理对象数组的方式进行反序列化。通过将您的代码更改为反序列化为List<Usari.Client>, 您可以做到这一点,并且应该解决此错误。


谢谢,它完美地运行了!现在我想将JSON对象的值写入Client类项,但要放在正确的位置(只有当JSON对象的名称与我的客户结构的项匹配时)。哪种方式最适合将JSON对象转换为Client类?谢谢。 - fondal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接