将Newtonsoft.Json.Linq.JArray转换为特定对象类型的列表

我有下面类型为{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; }
}

我对编程相当陌生,我不确定这是否可行。任何帮助与工作实例将非常感激。

324750 次浏览

只需调用array.ToObject<List<SelectableEnumItem>>()方法。它会返回你需要的东西。

文档:将JSON转换为类型

问题中的例子是一个更简单的例子,属性名在json和代码中完全匹配。如果属性名称不完全匹配,例如json中的属性是"first_name": "Mark",而代码中的属性是FirstName,则使用选择方法,如下所示

List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
FirstName = (string)x["first_name"],
Selected = (bool)x["selected"]
}).ToList();

我可以想出不同的方法来达到同样的效果

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) });

请注意,在上述解决方案中,我使用了动态对象

我可以想到更多的解是上述解的组合。但我认为它涵盖了几乎所有可用的方法。

我自己用第一个

在我的案例中,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
}

项目数组到客户端列表的转换如下所示:

 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);
}
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 Count,使用Loop转换为List

       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());
}