我正在使用Newtonsfot Json Converter搜索有关反序列化的所有问题。但我无法在我的代码中找到问题。所以我放在这里,寻求帮助。
来自visual studio的消息错误:
无控制 - Newtonsoft.Json.JsonSerializationException 的HResult = -2146233088 Message =无法将当前JSON数组(例如[1,2,3])反序列化为“APIEffilogics.Usuari + Client”类型,因为该类型需要 要正确反序列化的JSON对象(例如{“name”:“value”})。 要修复此错误,请将JSON更改为JSON对象(例如{“name”:“value”})或将反序列化类型更改为数组或 实现集合接口的类型(例如ICollection,IList) 像可以从JSON数组反序列化的List。 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消息所有项的数组。
由于
答案 0 :(得分:3)
尝试
var jsondata = JsonConvert.DeserializeObject<List<Usuari.Client>>(info);
这解决了该问题,因为例外表明:
要修复此错误,请将JSON更改为JSON对象(例如 {“name”:“value”})或将反序列化类型更改为数组或a 实现集合接口的类型(例如ICollection,IList) 像可以从JSON数组反序列化的List
重点强调突出重点
您收到的HTTP响应是一个对象数组,因此您需要以可以处理对象数组的方式对其进行反序列化。通过更改您的代码以反序列化为List<Usari.Client>
,您只需执行此操作即可解决错误。