C# Newtonsoft JSON使用HttpWebResponse反序列化

C# Newtonsoft JSON使用HttpWebResponse反序列化,c#,json,serialization,C#,Json,Serialization,我搜索了所有关于Newtonsfot Json转换器反序列化的问题。但我无法在代码中找到问题。所以我把它放在这里,请求帮助 来自visual studio的消息错误: 无se controlóNewtonsoft.Json.JsonSerializationException异常 HResult=-2146233088 Message=无法将当前JSON数组(例如[1,2,3])反序列化为类型“APIEffilogics.Usuari+Client”,因为该类型需要 JSON对象(例如{“nam

我搜索了所有关于Newtonsfot Json转换器反序列化的问题。但我无法在代码中找到问题。所以我把它放在这里,请求帮助

来自visual studio的消息错误:

无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***************************//
}
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)
{
   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();
       }
     }
}
这些是课程:

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***************************//
}
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类节点:Usuari//est结构节点
{            
[JsonProperty(“限额”)]
公共整数限制{get;set;}
[JsonProperty(“抵销”)]
公共整数偏移量{get;set;}
[JsonProperty(“节点”)]
公共列表节点_sub{get;set;}
}
公共类节点\子节点:节点
{
[JsonProperty(“id”)]
公共字符串nid{get;set;}
[JsonProperty(“全局id”)]
公共字符串gid{get;set;}
[JsonProperty(“描述”)]
公共字符串描述符{get;set;}
[JsonProperty(“房间id”)]
公共字符串rid{get;set;}
[JsonProperty(“楼层id”)]
公共字符串fid{get;set;}
[JsonProperty(“客户id”)]
公共字符串cid{get;set;}
[JsonProperty(“建筑id”)]
公共字符串bid{get;set;}
[JsonProperty(“节点模型id”)]
公共字符串模型{get;set;}
[JsonProperty(“nodetype_id”)]
公共字符串类型{get;set;}
}
代码与之前相同,只是我添加了以下句子:

jsonnode = JsonConvert.DeserializeObject<List<Usuari.Node>>(info);
jsonnode=jsonvenert.反序列化对象(info);
为什么我会犯同样的错误
List
是一个数组,包含JSON消息的所有项

谢谢

试试看

var jsondata = JsonConvert.DeserializeObject<List<Usuari.Client>>(info);
var jsondata=JsonConvert.DeserializeObject(信息);
正如例外情况所表明的那样,这解决了这个问题:

要修复此错误,请将JSON更改为JSON对象(例如。 {“name”:“value”})或将反序列化类型更改为数组或 实现集合接口的类型(例如ICollection、IList) 类似于可以从JSON数组反序列化的列表

为突出重点而增加的强调


您收到的HTTP响应是一个对象数组,因此您需要以能够处理对象数组的方式对其进行反序列化。通过将代码更改为反序列化为
列表
,您就可以做到这一点,它应该可以解决错误。

谢谢,它工作得非常好!!现在,我想将JSON对象的值写入客户机类项中,但要写入正确的位置(仅当JSON对象的名称与我的客户机结构项匹配时)。将JSON对象转换为客户机类的最佳形式是什么??谢谢