[英]JSON to Devexpress Winforms LookUpEdit Control
我的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轉換為Collection :
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框架,它們提供了很棒的功能,例如您可以通過DataSource向導選擇JSON Object,因此無需進行此類編碼。
如果使用的是舊版本,則可以使用IEnumerable<T>.Select(x=>x.xyz)
功能來迭代json的所有值,並通過Lookup.properies.items.add()將其放入lookupEdit。
謝謝
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.