当前位置: 代码迷 >> 综合 >> Unable to cast object of type ‘Newtonsoft.Json.Linq.JArray‘ to type ‘Newtonsoft.Json.Linq.JObject‘.
  详细解决方案

Unable to cast object of type ‘Newtonsoft.Json.Linq.JArray‘ to type ‘Newtonsoft.Json.Linq.JObject‘.

热度:14   发布时间:2023-12-06 01:17:05.0

原始数据:

string test=“[{\"value\":1,\"text\":\"1\"},{\"value\":2,\"text\":\"2\"}]”

错误调用:

 JObject  jsonStr = (JObject)JsonConvert.DeserializeObject(test)

引发报错:

Unable to cast object of type ‘Newtonsoft.Json.Linq.JArray‘ to type ‘Newtonsoft.Json.Linq.JObject‘.
 public class dict{ /// <summary>/// 字典id/// </summary>public int value { get; set; }/// <summary>/// 字典值/// </summary>public string text { get; set; }}

解决方案一:

   var testJArray = JArray.Parse(test);var  testJson = testJArray .ToObject<List<dict>>();

解决方案二:

  var testJson= JsonConvert.DeserializeObject<List<dict>>(test);
  相关解决方案