2014-10-07 207 views
4

我正在用Newtonsfot Json Converter搜索关于反序列化的所有问题。但我无法在我的代码中找到问题。所以我就放在这里寻求帮助。Newtonsoft JSON使用HttpWebResponse反序列化

从视觉工作室消息错误:

无SE控制0 Newtonsoft.Json.JsonSerializationException 的HResult = -2146233088 消息=无法反序列化当前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": "[email protected]", 
    "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 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消息项的数组。

感谢

回答

3

尝试

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

这解决了问题,因为异常提示:

要解决这个错误要么改变JSON的JSON对象(例如 {“名称“:”value“})或将反序列化类型更改为实现集合接口的数组或类型(例如的ICollection,IList的) 类似的列表,可以从一个JSON数组进行反序列化

着重强调要突出最关键的一点

您收到的HTTP响应对象的数组,所以你需要deserialise它一种可以处理一系列对象的方法。通过改变你的代码到反序列化到List<Usari.Client>你就是这样做的,它应该能够解决这个错误。

+0

谢谢你完美的作品!现在我想将JSON对象的值写入客户端类项目中,但在正确的位置(仅当JSON对象的名称与我的客户端结构的项目匹配时)。将JSON对象转换为客户端类的最佳形式是?谢谢 – fondal 2014-10-07 11:17:51

相关问题