[英]Newtonsoft JSON deserialize using HttpWebResponse
我正在使用Newtonsfot Json Converter搜索有關反序列化的所有問題。 但我無法在我的代碼中找到問題。 所以我放在這里,尋求幫助。
來自visual studio的消息錯誤:
無控制 - Newtonsoft.Json.JsonSerializationException HResult = -2146233088 Message =無法將當前JSON數組(例如[1,2,3])反序列化為類型'APIEffilogics.Usuari + Client',因為該類型需要JSON對象(例如{“名稱“:”值“})正確反序列化。 要修復此錯誤,請將JSON更改為JSON對象(例如{“name”:“value”})或將反序列化類型更改為數組或實現集合接口的類型(例如ICollection,IList),例如List從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 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消息的所有項的數組。
謝謝
嘗試
var jsondata = JsonConvert.DeserializeObject<List<Usuari.Client>>(info);
這解決了該問題,因為例外情況表明:
要修復此錯誤,請將JSON更改為JSON對象(例如{“name”:“value”})或將反序列化類型更改為數組或實現集合接口的類型(例如ICollection,IList),例如List從JSON數組反序列化
重點強調突出重點
您收到的HTTP響應是一個對象數組,因此您需要以可以處理對象數組的方式對其進行反序列化。 通過將您的代碼更改為反序列化為List<Usari.Client>
您只需執行此操作即可解決錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.