![](/img/trans.png)
[英]Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'System.Collections.Generic.List`
[英]Convert Newtonsoft.Json.Linq.JArray to a list of specific object type
我有以下类型{Newtonsoft.Json.Linq.JArray}
变量。
properties["Value"] {[
{
"Name": "Username",
"Selected": true
},
{
"Name": "Password",
"Selected": true
}
]}
我想要完成的是将其转换为List<SelectableEnumItem>
,其中SelectableEnumItem
是以下类型:
public class SelectableEnumItem
{
public string Name { get; set; }
public bool Selected { get; set; }
}
我对编程很新,我不确定这是否可行。 任何有关工作示例的帮助将不胜感激。
只需调用array.ToObject<List<SelectableEnumItem>>()
方法。 它会返回你需要的东西。
文档: 将JSON转换为类型
问题中的示例是一个更简单的情况,其中属性名称在json和代码中完全匹配。 如果属性名称不完全匹配,例如json中的属性为"first_name": "Mark"
,代码中的属性为FirstName
则使用Select方法 ,如下所示
List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
FirstName = (string)x["first_name"],
Selected = (bool)x["selected"]
}).ToList();
在我的情况下API返回值如下所示:
{
"pageIndex": 1,
"pageSize": 10,
"totalCount": 1,
"totalPageCount": 1,
"items": [
{
"firstName": "Stephen",
"otherNames": "Ebichondo",
"phoneNumber": "+254721250736",
"gender": 0,
"clientStatus": 0,
"dateOfBirth": "1979-08-16T00:00:00",
"nationalID": "21734397",
"emailAddress": "sebichondo@gmail.com",
"id": 1,
"addedDate": "2018-02-02T00:00:00",
"modifiedDate": "2018-02-02T00:00:00"
}
],
"hasPreviousPage": false,
"hasNextPage": false
}
将items数组转换为客户端列表的处理如下所示:
if (responseMessage.IsSuccessStatusCode)
{
var responseData = responseMessage.Content.ReadAsStringAsync().Result;
JObject result = JObject.Parse(responseData);
var clientarray = result["items"].Value<JArray>();
List<Client> clients = clientarray.ToObject<List<Client>>();
return View(clients);
}
我可以想到实现相同的不同方法
IList<SelectableEnumItem> result= array;
或者(我有一些情况,这个不能很好地工作)
var result = (List<SelectableEnumItem>) array;
或使用linq扩展名
var result = array.CastTo<List<SelectableEnumItem>>();
要么
var result= array.Select(x=> x).ToArray<SelectableEnumItem>();
或者更明确地说
var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });
请注意以上解决方案我使用的是动态对象
我可以想到一些解决方案,它们是上述解决方案的组合。 但我认为它涵盖了几乎所有可用的方法。
我自己用的是第一个
using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;
public List<string> GetJsonValues(string filePath, string propertyName)
{
List<string> values = new List<string>();
string read = string.Empty;
using (StreamReader r = new StreamReader(filePath))
{
var json = r.ReadToEnd();
var jObj = JObject.Parse(json);
foreach (var j in jObj.Properties())
{
if (j.Name.Equals(propertyName))
{
var value = jObj[j.Name] as JArray;
return values = value.ToObject<List<string>>();
}
}
return values;
}
}
使用IList获取JArray计数和使用循环转换为列表
var array = result["items"].Value<JArray>();
IList collection = (IList)array;
var list = new List<string>();
for (int i = 0; i < collection.Count; j++)
{
list.Add(collection[i].ToString());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.