JSON to Devexpress Winforms LookUpEdit Control

时间:2018-04-12 19:16:49

标签: c# json devexpress devexpress-windows-ui

我的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  文件?

2 个答案:

答案 0 :(得分:1)

Documentation开始,您需要将数据源作为实现System.Collections.IListSystem.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;
    }
}

或者,您可以将此方法用于convert from JSON to a 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

答案 1 :(得分:0)

借助新的DevExpress框架,它们提供了很棒的功能,例如您可以通过DataSource向导选择JSON对象,因此无需进行此类编码。

如果您使用的是旧版本,则可以使用IEnumerable<T>.Select(x=>x.xyz)功能来迭代json的所有值,并通过Lookup.properies.items.add()放入lookupEdit中。

谢谢