c# - 将对象添加到 JSON 文件
问题描述
我正在创建一个软件,在该软件上添加了配置文件功能,用户可以在其中创建配置文件以更快地加载他的信息。为了存储这些信息,我使用了一个 JSON 文件,其中包含与配置文件一样多的对象。
这是包含配置文件时 JSON 文件的格式(不是实际的,示例):
{
"Profile-name": {
"form_email": "example@example.com",
//Many other informations...
}
}
这是我用来编写 JSON 及其内容的代码:
string json = File.ReadAllText("profiles.json");
dynamic profiles = JsonConvert.DeserializeObject(json);
if (profiles == null)
{
File.WriteAllText(jsonFilePath, "{}");
json = File.ReadAllText(jsonFilePath);
profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);
}
profiles.Add(profile_name.Text, new Profile_Name { form_email = form_email.Text });
var newJson = JsonConvert.SerializeObject(profiles, Formatting.Indented);
File.WriteAllText(jsonFilePath, newJson);
profile_tr.Nodes.Add(profile_name.Text, profile_name.Text);
debug_tb.Text += newJson;
但是当profiles.json文件完全为空时,配置文件被成功写入,但是当我在另一个已经存在的情况下尝试添加一个配置文件时,我得到这个错误:
The best overloaded method match for 'Newtonsoft.Json.Linq.JObject.Add(string, Newtonsoft.Json.Linq.JToken)' has some invalid arguments
就profiles.Add();
行了。顺便说一句,您会注意到{}
如果文件为空,我需要通过一种非平凡的方式在文件中添加,也许它与错误有关?预期的输出将是这个 JSON 文件:
{
"Profile-name": {
"form_email": "example@example.com",
//Many other informations...
},
"Second-profile": {
"form_email": "anotherexample@example.com"
//Some other informations...
}
}
解决方案
好的,我通过再次阅读我的代码找到了,所以我只是替换 dynamic profiles = JsonConvert.DeserializeObject(json);
为dynamic profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);
. 但它仍然没有解决我用来添加{}
到我的文件的非平凡方式......
推荐阅读
- c# - “TypeInitializationException 未处理”异常 c#
- terminal - kill 实际上并没有终止幽灵进程
- python - 当我尝试在 URL 有破折号时拨打电话时,Slumber Python 库失败(-)
- excel - 当在另一列中满足条件时,Excel 公式计算一列中的行数
- mongodb - MongoDB 区分然后过滤
- react-native - React Native for Android TV - 焦点输入/输出事件问题
- html - 在 flexbox 中缩放图像
- python - 如何根据用户输入调用函数?
- angularjs - AngularJS控制器作为:承诺不更新视图
- javascript - 为什么只点击一个表单的提交按钮时所有表单都提交了?