2014-10-07 127 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

相關問題