[英]C# Deserialize JSON list WinForm Combobox
我正在尝试构建一个正在读取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循环,因为它将显示列表中的所有描述字段。
感谢提供的任何帮助。 提前致谢。
使用ComboBox SelectedIndexChanged事件。 在事件中,用组合框的值填充文本框。 请参考以下代码:
// Add this in the Form Initialization or Form_Load()
boxOptions.SelectedIndexChanged += new
system.EventHandler(boxOptions_SelectedIndexChanged);
// Event Handler
private void boxOptions_SelectedIndexChanged(object sender, System.EventArgs e)
{
txtBox1.Text = comboBox_Code1.Text;
}
首先,您需要将json
对象转换为C#列表。
然后只需放置一个where条件与您的条件匹配,然后将该对象返回到UI
。
public class YourModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
class YourClass
{
public IEnumerable<YourModel> YourModels{ get; set; }
}
string jsonString = //your json will go here
JavaScriptSerializer serializer = new JavaScriptSerializer();
YourClass data= serializer.Deserialize<YourClass >(jsonString);
}
请检查
私有变量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属性上使用SelectedIndexChange
事件
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int nIndex = comboBox1.SelectedIndex;
string strDesc = x[nIndex].Description;
textBox1.Text = strDesc;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.