首页 > 解决方案 > 将对象添加到 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 argumentsprofiles.Add();行了。顺便说一句,您会注意到{}如果文件为空,我需要通过一种非平凡的方式在文件中添加,也许它与错误有关?预期的输出将是这个 JSON 文件:

{
  "Profile-name": {
    "form_email": "example@example.com",
    //Many other informations...
  },
  "Second-profile": {
    "form_email": "anotherexample@example.com"
    //Some other informations...
  }
}

标签: c#json

解决方案


好的,我通过再次阅读我的代码找到了,所以我只是替换 dynamic profiles = JsonConvert.DeserializeObject(json);dynamic profiles = JsonConvert.DeserializeObject<Dictionary<string, Profile_Name>>(json);. 但它仍然没有解决我用来添加{}到我的文件的非平凡方式......


推荐阅读