JSON to Devexpress Winforms LookUpEdit Control

问题描述 投票:0回答:2

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

c# json devexpress devexpress-windows-ui
2个回答
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

0
投票

使用新的DevExpress框架,它们提供了很棒的功能,就像您可以通过DataSource向导选择JSON对象一样,因此您无需进行此类编码。

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

谢谢

© www.soinside.com 2019 - 2024. All rights reserved.