[英]Cannot deserialize the current JSON array (e.g. [1,2,3]) into type '' because the type requires a JSON object (e.g. {“name”:“value”})
[英]Cannot deserialize the current JSON object (e.g. {“name”:“value”}) into type requires a JSON array (e.g. [1,2,3]) to deserialize correctly
我在哪里缺少信息? 我需要反序列化以下 JSON 字符串。
{
"data": [
{
"FirstName": "Test",
"LastName": "Test"
}
]
}
為此,我定義了我的 LoadData 操作方法:
public async Task<ActionResult> LoadData()
{
string apiUrl = "URL";
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(apiUrl);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var input = new { depot = "DATA", fromDate = "2020-06-06", toDate = "2020-06-06" };
var response1 = await client.PostAsJsonAsync("DATAOne", input);
if (response1.IsSuccessStatusCode)
{
var data = await response1.Content.ReadAsStringAsync();
var table = JsonConvert.DeserializeObject<List<PartOne>>(data);
}
}
return View();
}
為此,我定義了我的 class:
public class PartOne
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
但是當我嘗試使用反序列化器時,它給出了一個異常。
{"Cannot deserialize the current JSON object (eg {"name":"value"}) into type 'System.Collections.Generic.List`1[InfluxDB.Serie]' because the type requires a JSON array (eg [1, 2,3]) 以正確反序列化。\r\n要修復此錯誤,請將 JSON 更改為 JSON 數組(例如 [1,2,3])或將反序列化類型更改為正常的 Z72AZ1CB0BEEF9EDB590 a primitive type like integer, not a collection type like an array or List) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.\r\nPath 'results' ,第 2 行,position 12。"}
您在這里有兩個選擇:
第一個選項,您缺少data
的包裝器 object
public class Wrapper<T>
{
public T Data { get; set; }
}
然后使用:
var table = JsonConvert.DeserializeObject<Wrapper<List<PartOne>>>(json).Data;
第二個選項,首先將其反序列化為 JObject 並訪問數據,然后將其反序列化為List<PartOne>
:
var jObj = JsonConvert.DeserializeObject(json) as JObject;
var jArr = jObj.GetValue("data");
var table = jArr.ToObject<List<PartOne>>();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.