无法将当前 JSON 对象(例如 {"name":"value"})反序列化为需要 JSON 数组(例如 [1,2,3])才能正确反序列化的类型

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 (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[InfluxDB.Serie]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.\r\nTo fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not 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', line 2, position 12."}

这里有两个选择:


第一个选项,您缺少 data

的包装器对象
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>>();