【发布时间】:2019-05-16 15:33:51
【问题描述】:
我正在通过使用 Web 服务 api 实现 GPS 跟踪系统。
错误:
Newtonsoft.Json.dll 中出现“Newtonsoft.Json.JsonSerializationException”类型的未处理异常
附加信息:无法将当前 JSON 数组(例如 [1,2,3])反序列化为类型“TrackingRequest.Devices”,因为该类型需要 JSON 对象(例如 {"name":"value"})来反序列化正确。
要修复此错误,请将 JSON 更改为 JSON 对象(例如 {"name":"value"})或将反序列化类型更改为数组或实现集合接口的类型(例如 ICollection、IList),例如可以从 JSON 数组反序列化的列表。也可以将 JsonArrayAttribute 添加到类型中以强制它从 JSON 数组中反序列化。
这是在 c# 中的 web 表单应用程序中,HttpClient 使用 Newtonsoft 的 json。
我的代码
using (HttpClient clientKey = new HttpClient())
{
clientKey.BaseAddress = new Uri("http://api.trackingdiary.com/");
clientKey.DefaultRequestHeaders.Add("Hive-Session", key);
clientKey.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage responseKey = clientKey.GetAsync("/v2/geo/devices/list").Result;
using (HttpContent contentkey = responseKey.Content)
{
Task<string> resultKey = contentkey.ReadAsStringAsync();
Devices obj = JsonConvert.DeserializeObject<Devices>(resultKey.Result);
Console.WriteLine();
}
}
我的班级:
class position
{
[JsonProperty("lat")]
public int lat { get; set; }
[JsonProperty("lng")]
public int lng { get; set; }
[JsonProperty("hdop")]
public int hdop { get; set; }
[JsonProperty("fix")]
public bool fix { get; set; }
}
class Devices
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("date_contacted")]
public string date_contacted { get; set; }
[JsonProperty("startup")]
public string startup { get; set; }
[JsonProperty("position")]
public position position { get; set; }
}
}
我想在 DataTable 中执行对象。
JSON 示例 JSON EXAMPLE
【问题讨论】:
-
您能否展示一个示例
json您正在使用的响应? -
C# 约定说你的属性应该是 PascalCased:
Id、Name、DateContacted等。它们不需要匹配传入的 JSON,由[JsonProperty("date_contacted")] -
没有看到 JSON 很难确定,但错误消息似乎很清楚:您正在尝试将数组转换为对象。
-
@TobySmith ThisIsPascalCaseNotCamelCase butThisIsCamelCase.
-
返回的 Json 是设备列表,而不是单个设备对象
标签: c# json object httpclient