前言
C#窗体应用操作json
有json格式为:
[
{
"key":"", //json标识符,可以理解为控件Name
"value":"", //控件的Text名称
"size":9, //控件大小
"formName":"" //控件属于哪一个窗体
},
{
"key":"",
"value":"",
"size":9,
"formName":""},
{
"key":"",
"value":"",
"size":9,
"formName":""}
...
]
现在需要将三份不同的json文件,根据key与formName实现增删改查等等,代码过长,截取片段思路。
主窗体页面展示:
增加窗体展示:
搜索功能
首先在窗体开始执行就搜索操作
search("");
//默认搜索全部,调用时,将自己的字段调用,模糊搜索出来
//查询
public void search(string keyword)
{
// 遍历文件列表,创建 DataTable 并填充数据
for (int i = 0; i < files.Length; i++)
{
// 读取 JSON 文件中的数据
List<Dictionary<string, object>> dataList = ReturnListJson(files[i]);
// 根据关键词筛选出符合条件的数据
var filteredDataList = dataList.Where(dataDict =>
dataDict.ContainsKey("Key") && dataDict["Key"].ToString().Contains(keyword) ||
dataDict.ContainsKey("Value") && dataDict["Value"].ToString().Contains(keyword) ||
dataDict.ContainsKey("formName") && dataDict["formName"].ToString().Contains(keyword))
.ToList();
// 创建 DataTable
DataTable dataTable = new DataTable();
....
// 创建一个 DataGridView 控件
// 创建一个按钮列,
DataGridViewButtonColumn deleteButtonColumn = new DataGridViewButtonColumn();
deleteButtonColumn.Name = "Delete";
deleteButtonColumn.HeaderText = "操作";
deleteButtonColumn.Text = "删除";
// 创建单元格样式并设置背景颜色
deleteButtonColumn.DefaultCellStyle.BackColor = Color.Red;
deleteButtonColumn.UseColumnTextForButtonValue = true;
// 将数据填充到 DataTable 中
foreach (Dictionary<string, object> dataDict in filteredDataList)
{
DataRow dataRow = dataTable.NewRow();
...
dataTable.Rows.Add(dataRow);
}
// 将 DataTable 绑定到对应的 DataGridView 上
switch (i)
{
case 0:
dgvData_Z.Columns.Clear();
dgvData_Z.Columns.Add(deleteButtonColumn);
dgvData_Z.DataSource = dataTable;
dgvData_Z.Columns[3].Width = 50;
// 将按钮列添加到控件中
break;
case 1:
...
break;
case 2:
...
break;
default:
break;
}
}
}
用于在多个 JSON 文件中搜索匹配关键字的方法。具体实现过程如下:
1. 遍历文件列表,读取 JSON 文件中的数据。
2. 对于每个文件的数据,根据关键字筛选出符合条件的数据,并将其放入一个新的 list 中。
3. 为每个文件创建一个 DataTable 对象,并添加列名。
4. 将步骤 2 中筛选出的数据逐行添加到 DataTable 中。
5. 将 DataTable 绑定到对应的 DataGridView 控件上。
6. 创建一个按钮列,用于删除对应 DataGridView 控件中的某条数据。
7. 最后将按钮列添加到每个 DataGridView 控件中。
通过这个方法,用户可以方便地在多个文件中查询匹配关键字的数据,并且可以通过删除按钮快速删除不需要的数据。
删除操作
当文件选中后操作:
当选择任意Datagridview的一行数据后,在下面修改框显示,如果点击的是删除键,则触发删除操作
//点击datagridview后,展示数据,//修改或者删除
private string path;
private void dgvData_CellClick(object sender, DataGridViewCellEventArgs e)
{
// 判断是否选中了行
if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
{
// 获取选中的行数据 0:删除 1:MCode 2:加工中心编号 3:size 4:HomeForm
// 获取选中的行数据
DataGridViewRow row = (sender as DataGridView).Rows[e.RowIndex];
// 获取选中行的 Key 和 formName 值
string key = row.Cells[1].Value.ToString();
string formName = row.Cells[4].Value.ToString();
// 根据 Key 和 formName 值查找对应的数据
List<Dictionary<string, object>> dataList;
switch ((sender as DataGridView).Name)
{
case "dgvData_Z":
dataList = ReturnListJson(files[0]);
path = files[0];
break;
case "dgvData_E":
dataList = ReturnListJson(files[1]);
path = files[1];
break;
case "dgvData_U":
dataList = ReturnListJson(files[2]);
path = files[2];
break;
default:
throw new ArgumentException("没有选择"); //抛出异常
}
// 判断点击的单元格是否是删除按钮所在列
if ((sender as DataGridView).Columns[e.ColumnIndex].Name == "Delete")
{
MessageBox.Show("删除操作");
}
else
{
//使用 string.IsNullOrWhiteSpace 方法进行检查,如果是空,则忽略该条件;否则,在查询中包含该条件,解除限制
Dictionary<string, object> dataDict = dataList.Find(d => d.ContainsKey("Key") && d["Key"].ToString().Equals(key) && (string.IsNullOrEmpty(formName) || d["formName"].ToString().Equals(formName)));
// 显示选中行的详细数据
if (dataDict != null)
{
switch ((sender as DataGridView).Name)
{
case "dgvData_Z":
...
break;
case "dgvData_E":
...
break;
case "dgvData_U":
...
break;
}
}
}
}
}
修改操作
设置三个按钮,点击后,获取text值传入HandleModifyBtnClick
private void btnZ_Click(object sender, EventArgs e)
{
HandleModifyBtnClick(dgvData_Z, files[0], txtKey, txtValue, txtSize, txtFormName);
}
private void btnE_click(object sender, EventArgs e)
{
HandleModifyBtnClick(dgvData_E, files[1], E_txtkey, E_txtValue, E_txtSize, E_txtForm);
}
private void btnU_click(object sender, EventArgs e)
{
HandleModifyBtnClick(dgvData_U, files[2], U_txtKey, U_txtValue, U_txtSize, U_txtForm);
HandleModifyBtnClick
//修改数据
private void HandleModifyBtnClick(DataGridView dgv, string jsonFilePath,
TextBox keyTextBox, TextBox valueTextBox, TextBox sizeTextBox, TextBox formNameTextBox)
{
// 获取选中行的 Key 和 formName 值
string selectKey = dgv.SelectedCells[1].Value.ToString();
string selectformName = dgv.SelectedCells[4].Value.ToString();
List<Dictionary<string, object>> dataList = ReturnListJson(jsonFilePath);
Dictionary<string, object> dataDict = dataList.Find(d =>
d.ContainsKey("Key") && d["Key"].ToString() == selectKey &&
d.ContainsKey("formName") && d["formName"].ToString() == selectformName);
// 更新数据
if (dataDict != null)
{
...
// 将更新后的数据保存到 JSON 文件中
string updatedJsonString = JsonConvert.SerializeObject(dataList, Formatting.Indented);
File.WriteAllText(jsonFilePath, updatedJsonString);
// 更新 DataGridView 中的数据
...
}
}
在实现点击“更新”按钮后,更新选中 DataGridView 中的数据以及对应的 JSON 文件中的数据。具体实现过程如下:
首先,获取当前选中行的 Key 和 formName 值,然后读取 JSON 文件,查找是否有与选中行匹配的字典项,如果存在,则将该字典项的值更新为新的值,并将更新后的数据保存到 JSON 文件中。
接着,遍历 DataGridView 中的每一行数据,查找与选中行匹配的行,并将该行中的数据更新为新的值。
需要注意的是,在更新 Size 值时,需要先将其转换为 float 类型再赋值。同时,在保存更新后的 JSON 数据时,使用了 JsonConvert.SerializeObject 方法来序列化 List<Dictionary<string, object>> 类型的数据,并使用 Formatting.Indented 进行格式化以便于查看和编辑。
运行效果图:
增加数据:
首先新建一个窗体
首先获取了各个控件的值,然后判断是否补全了内容。如果没有补全,会弹出提示框,询问是否继续添加数据,如果选择继续,则使用 for 循环遍历每个 JSON 文件,并调用 AddJsonItem 方法添加数据;如果已经补全了内容,直接遍历每个 JSON 文件并调用 AddJsonItem 方法添加数据。
需要注意的是,这里使用了三元运算符来判断加入哪个 Jsonvalue 的值。
//增加数据
private void btnAdd_Click(object sender, EventArgs e)
{
string Jsonkey = this.txtKey.Text.Trim();
string Z_Jsonvalue = this.Z_txtValue.Text.Trim();
string E_Jsonvalue = this.E_txtValue.Text.Trim();
string U_Jsonvalue = this.U_txtValue.Text.Trim();
float Jsonsize = (float)numSize.Value;
string JsonformName = this.txtForm.Text.Trim();
if (string.IsNullOrEmpty(Z_Jsonvalue) || string.IsNullOrEmpty(E_Jsonvalue) || string.IsNullOrEmpty(U_Jsonvalue))
{
if (MessageBox.Show("内容还没补全,是否继续", "提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
for(int i = 0; i < files.Length; i++)
{
AddJsonItem(files[i], Jsonkey, i == 0 ? Z_Jsonvalue : i == 1 ? E_Jsonvalue : U_Jsonvalue, Jsonsize, JsonformName);
}
MessageBox.Show("数据已添加到 json文件中");
}
}
else
{
for (int i = 0; i < files.Length; i++)
{
AddJsonItem(files[i], Jsonkey, i == 0 ? Z_Jsonvalue : i == 1 ? E_Jsonvalue : U_Jsonvalue, Jsonsize, JsonformName);
}
MessageBox.Show("数据已添加到 json文件中");
}
向 JSON 文件中添加一条新的数据。具体过程如下:
首先,读取指定路径下的 JSON 文件,然后根据传入的参数 Jsonkey 和 formName 查找是否已经存在符合条件的字典项,如果存在则弹出提示信息并返回。其中使用了 Any 方法对查询结果进行判断。
如果不存在符合条件的字典项,则构造一个新的字典项,包括 Key、Value、Size 和 formName 四个字段,并将其添加到 dataList 中。
接着,将 dataList 列表序列化为 JSON 字符串,并使用 StreamWriter 将其写入到指定路径的文件中。
最后,清空文本框的内容。
需要注意的是,在使用 StreamWriter 写入文件时,如果出现异常,需要捕获并弹出错误信息。同时,在写入前需要清空文本框的内容,以便于下次输入数据。
//读取json文件
// 根据 Key 和 formName 值查找对应的数据
string jsonString = File.ReadAllText(path);
List<Dictionary<string, object>> dataList = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jsonString);
// 读取 JSON 文件中的数据
// 根据关键词筛选出符合条件的数据
var found = dataList.Any(d => d.ContainsKey("Key")
&& d["Key"].ToString().Contains(Jsonkey) && d.ContainsKey("formName") && d["formName"].ToString().Contains(formName));
if (found)
{
MessageBox.Show(path+"已经存在该字段的数据");
return;
}
//构造新的字典项
Dictionary<String, object> newItem = new Dictionary<string, object>();
newItem.Add("Key", Jsonkey);
newItem.Add("Value", Jsonvalue);
newItem.Add("Size", Jsonsize);
newItem.Add("formName", formName);
dataList.Add(newItem);
//将json列表序列化写入文件中
try
{
using (StreamWriter writer = new StreamWriter(path))
{
writer.Write(JsonConvert.SerializeObject(dataList));
}
}
catch (Exception ex)
{
MessageBox.Show("写入" + path + ".Json文件出错" + ex.Message);
return;
}
最后,三个文件共同修改操作完成,可以在程序中
这份代码主要实现了一个操作 JSON 文件的功能,包括查找、添加和更新数据。具体实现过程如下:
1. 更新数据:根据选中的 DataGridView 中的行数据,查找对应的 JSON 文件,更新其中对应的字典项的值以及 DataGridView 中的显示。其中使用了 JsonConvert.SerializeObject 方法来序列化 List<Dictionary<string, object>> 类型的数据,并使用 Formatting.Indented 进行格式化,使其易于查看。
2. 添加数据:将用户输入的字段信息存储到 Dictionary<string, object> 对象中,然后将其添加到 JSON 文件中。其中使用了 Any 方法对查询结果进行判断,如果存在符合条件的字典项则弹出提示信息并返回。同时,使用 StreamWriter 将 dataList 列表序列化为 JSON 字符串,并写入到指定路径的文件中。
3. 查找数据:根据传入的 JSONkey 和 formName 值查找含有对应字段的字典项,并返回结果(使用了 Contains 方法)。
在操作 JSON 文件时,需要捕获可能出现的异常,并进行相应的处理。同时,需要对读取到的 JSON 数据进行类型转换,以便于后续的操作。
以上代码提供学习与交流。