[英]Convert Newtonsoft.Json.Linq.JArray to a list of specific object type
I have the following variable of type {Newtonsoft.Json.Linq.JArray}
. 我有以下类型
{Newtonsoft.Json.Linq.JArray}
变量。
properties["Value"] {[
{
"Name": "Username",
"Selected": true
},
{
"Name": "Password",
"Selected": true
}
]}
What I want to accomplish is to convert this to List<SelectableEnumItem>
where SelectableEnumItem
is the following type: 我想要完成的是将其转换为
List<SelectableEnumItem>
,其中SelectableEnumItem
是以下类型:
public class SelectableEnumItem
{
public string Name { get; set; }
public bool Selected { get; set; }
}
I am rather new to programming and I am not sure whether this is possible. 我对编程很新,我不确定这是否可行。 Any help with working example will be greatly appreciated.
任何有关工作示例的帮助将不胜感激。
Just call array.ToObject<List<SelectableEnumItem>>()
method. 只需调用
array.ToObject<List<SelectableEnumItem>>()
方法。 It will return what you need. 它会返回你需要的东西。
Documentation: Convert JSON to a Type 文档: 将JSON转换为类型
The example in the question is a simpler case where the property names matched exactly in json and in code. 问题中的示例是一个更简单的情况,其中属性名称在json和代码中完全匹配。 If the property names do not exactly match, eg property in json is
"first_name": "Mark"
and the property in code is FirstName
then use the Select method as follows 如果属性名称不完全匹配,例如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();
The API return value in my case as shown here: 在我的情况下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
}
The conversion of the items array to list of clients was handled as shown here: 将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);
}
I can think of different method to achieve the same 我可以想到实现相同的不同方法
IList<SelectableEnumItem> result= array;
or (i had some situation that this one didn't work well) 或者(我有一些情况,这个不能很好地工作)
var result = (List<SelectableEnumItem>) array;
or use linq extension 或使用linq扩展名
var result = array.CastTo<List<SelectableEnumItem>>();
or 要么
var result= array.Select(x=> x).ToArray<SelectableEnumItem>();
or more explictly 或者更明确地说
var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });
please pay attention in above solution I used dynamic Object 请注意以上解决方案我使用的是动态对象
I can think of some more solutions that are combinations of above solutions. 我可以想到一些解决方案,它们是上述解决方案的组合。 but I think it covers almost all available methods out there.
但我认为它涵盖了几乎所有可用的方法。
Myself I use the first one 我自己用的是第一个
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;
}
}
Use IList to get the JArray Count and Use Loop to Convert into List 使用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.