c# - 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循环,因为它将显示列表中的所有描述字段。
我感谢提供的任何帮助。提前致谢。
解决方案
请检查
私有变量
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;
}
推荐阅读
- node.js - 如何配置 babelify 将 javascript 文件转换为兼容 IE 11
- python - 从图像坐标反向投影到世界坐标(相对于地图)?
- c# - 如何使用 InOut 参数作为 RefCursor 调用 Postgres V11 存储过程(非函数)?使用 Npgsql v4.0.8
- mongodb - 聚合mongodb中具有多个条件的addToSet
- sql - PL/SQL: ORA-00920: 无效的关系运算符
- python - 如何在 RetrieveUpdateDestroyAPIView 中更改序列化数据的值
- c - 为什么 `ld` 无法链接该程序?
- c# - What design patterns can be used to architecture this?
- angular - 将使用 ng-class 的类添加到 mat-menu
- sql - 如何明智地从表类别中获取最后一个值?