My JSON file content like this:
{
01: "One",
02: "Two",
03: "Three",
04: "Four",
05: "Five",
06: "Six",
07: "Seven",
08: "Eight",
09: "Nine",
10: "Ten"
}
And I am using Newtonsoft.Json
library. I tried like this:
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"));
It gives an error like this: '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?)
How can I fiil the Devexpress Winforms LookUpEdit from JSON file?
From the Documentation, you need your data source to be any object that implements the System.Collections.IList
or System.ComponentModel.IListSource
interfaces. This presents a challenge as to how you actually want to convert your JSON object to a list. For example, what are you calling your keys ("01", "02", ...)? And are you sure that JSON is properly formatted (01
instead of "01"
)?
The following is how you can convert your JSON object to an object using the IList interface.
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;
}
}
Alternatively, you can use this method to convert from JSON to a Collection, if you can modify your initial input a bit:
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