首页 > 解决方案 > C# 反序列化 JSON 列表 WinForm 组合框

问题描述

我正在尝试构建一个正在读取 json 文件的应用程序,将其转换为 c# 对象并根据用户从组合框中选择的项目打印输出。

JSON 文件如下所示

[
{
    "Description": "Some text here.",
    "Id": 1,
    "Name": "Option 1",
},
{
    "Description": "Another different text here",
    "Id": 2,
    "Name": "Option 2",

}

]

该类定义如下:

    public class Incident
{

    public Incident()
    {
    }
    public Incident(int id, string name, string description)
    {
        Id = id;
        Name = name;
        Description = description;
    }

    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

我正在使用名称字段中的值填充组合框,如下所示:

            var jsonPath = Path.Combine(Environment.CurrentDirectory, "Data", "configuration.json");
            // Read values from file
            var strReadJson = File.ReadAllText(jsonPath);
            // Convert to Json Object
            var x = JsonConvert.DeserializeObject<List<Incident>>(strReadJson);

            foreach (var option in x.Select(p => p.Name))
            {
                boxOptions.Items.Add(option);
                boxOptions.Sorted = true;
            }

现在我想根据从组合框中选择的名称用事件的描述字段填充一个文本框,这是我被卡住的部分。

因此,如果用户从组合框中选择名称“选项 1”,则文本框应显示“此处的某些文本”,如果选择“选项 2”,则应显示“另一个不同的文本”。

我不知道是否应该在这里应用foreach循环,因为它将显示列表中的所有描述字段。

我感谢提供的任何帮助。提前致谢。

标签: c#jsonwinforms

解决方案


请检查

私有变量 List<Incident> x = new List<Incident>();

读取文件(使用您的代码)

    private void frmSampleJson_Load(object sender, EventArgs e)
    {
        string Json = File.ReadAllText(@"d://read.txt").ToString();
        //Read the Array
        JArray array = JArray.Parse(Json);
        //Sort the Array
        JArray sorted = new JArray(array.OrderBy(obj => (string)obj["Name"]));
        //Added sorted JArray to List<Incident>
        x = sorted.ToObject<List<Incident>>();

        foreach (var option in x.Select(p => p.Name))
        {
            comboBox1.Items.Add(option);                
        }
    }

现在在 Combox Properties UsedSelectedIndexChange事件上

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        int nIndex = comboBox1.SelectedIndex;
        string strDesc = x[nIndex].Description;
        textBox1.Text = strDesc;
    }

关于选择组合框项目 1

关于选择组合框项目 2


推荐阅读