[英]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.