我的JSON文件内容如下:
{
01: "One",
02: "Two",
03: "Three",
04: "Four",
05: "Five",
06: "Six",
07: "Seven",
08: "Eight",
09: "Nine",
10: "Ten"
}
我正在使用Newtonsoft.Json
库。我试过这样:
var json = File.ReadAllText(@"numbers.json");
var array = JObject.Parse(json);
lookUpEdit1.Properties.DropDownRows = array.Count > 10 ? 10 : array.Count;
lookUpEdit1.Properties.DisplayMember = "Key";
lookUpEdit1.Properties.ValueMember = "Value";
lookUpEdit1.Properties.DataSource = array.ToList();
lookUpEdit1.Properties.Columns.Add(new LookUpColumnInfo("Key"));
它给出了如下错误:'JObject' does not contain a definition for 'ToList' and no extension method 'ToList' accepting a first argument of type 'JObject' could be found (are you missing a using directive or an assembly reference?)
我怎样才能从JSON中获取Devexpress Winforms LookUpEdit。 文件?
在文档中,您需要数据源是实现System.Collections.IList
或System.ComponentModel.IListSource
接口的任何对象。这给您实际希望如何将 JSON 对象转换为列表带来了挑战。例如,你怎么称呼你的钥匙("01"、"02",...(?您确定 JSON 格式正确(01
而不是"01"
(吗?
以下是使用 IList 接口将 JSON 对象转换为对象的方法。
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
public class Program
{
public static void Main()
{
string json = @"
{
'01':'One',
'02':'Two',
'03':'Three',
'04':'Four',
'05':'Five',
'06':'Six',
'07':'Seven',
'08':'Eight',
'09':'Nine',
'10':'Ten'
}";
JObject o = JObject.Parse(json);
NumberObject zero = new NumberObject("00", "zero");
List<NumberObject> list = new List<NumberObject>();
foreach (JProperty p in o.Properties())
{
NumberObject num = new NumberObject(p.Name, (string)p.Value);
list.Add(num);
}
// now list can be used as your data source as it is of type List<NumberObject>
}
}
public class NumberObject
{
public string Name {get; set;}
public string Value {get; set;}
public NumberObject(string numName, string numValue)
{
Name = numName;
Value = numValue;
}
}
或者,如果可以稍微修改初始输入,则可以使用此方法从 JSON 转换为集合:
string json = @"{
'd': [
{
'Name': 'John Smith'
},
{
'Name': 'Mike Smith'
}
]
}";
JObject o = JObject.Parse(json);
JArray a = (JArray)o["d"];
IList<Person> person = a.ToObject<IList<Person>>();
Console.WriteLine(person[0].Name);
// John Smith
Console.WriteLine(person[1].Name);
// Mike Smith
使用新的DevExpress框架,它们提供了很棒的功能,例如您可以通过数据源向导选择JSON对象,因此您无需进行此类编码。
如果您使用旧版本,您可以使用IEnumerable<T>.Select(x=>x.xyz)
功能来迭代 json 的所有值,并通过 Lookup.properies.items.add(( 放入 lookupEdit 中;
谢谢