C# 将 Newtonsoft.Json.Linq.JArray 转换为特定对象类型的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13565245/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Newtonsoft.Json.Linq.JArray to a list of specific object type
提问by Mdb
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 SelectableEnumItemis 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.
我对编程很陌生,我不确定这是否可行。任何有关工作示例的帮助将不胜感激。
采纳答案by HoberMellow
Just call array.ToObject<List<SelectableEnumItem>>()method. It will return what you need.
只需调用array.ToObject<List<SelectableEnumItem>>()方法。它会返回你需要的东西。
Documentation: Convert JSON to a Type
文档:将 JSON 转换为类型
回答by Souvik Basu
The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark"and the property in code is FirstNamethen use the Select methodas follows
问题中的示例是一个更简单的情况,其中属性名称在 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();
回答by Mo Hrad A
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
我自己我用第一个
回答by stephen ebichondo
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": "[email protected]",
"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);
}
回答by Mohammed Hossen
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;
}
}
回答by Kumaran
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());
}

