首页 > 解决方案 > C# 将值添加到 JSON 文件而不更改初始 JSON 格式

问题描述

我想要的是:

在 JSON 文件中的特定位置添加属性(对于这种情况,我想在 {"name":"Andrew"} 之后添加 {"name2":"Tom} )而不更改其格式(空的新行)

当前 JSON

    {
    "Profiles": [
        {
            "Properties": {

                "color": "blue",
                "shape": "circle",
                "fruit": "apple",
            
                "name": "Andrew",

                "username": "ad11",
                "Password": "pass",

                "country": "France",
                "region": "Europe"
            }
        }
    ]
}

当前代码

        var json = File.ReadAllText(path);
        var Jobect = JObject.Parse(json);

        Jobect["Profiles"][0]["Properties"]["name2"] = "Tom";

        File.WriteAllText(path, Jobect.ToString());

结果 JSON

 {
   "Profiles": [
     {
       "Properties": {
         "color": "blue",
         "shape": "circle",
         "fruit": "apple",
         "name": "Andrew",
         "username": "ad11",
         "Password": "pass",
         "country": "France",
         "region": "Europe",
         "name2": "Tom"
       }
     }
   ]
 }

所需的 JSON

{
    "Profiles": [
        {
            "Properties": {

                "color": "blue",
                "shape": "circle",
                "fruit": "apple",
            
                "name": "Andrew",
                "name2": "Tom,

                "username": "ad11",
                "Password": "pass",

                "country": "France",
                "region": "Europe"
            }
        }
    ]
}

综上所述。如何在 JSON 文件中的特定位置添加属性而不更改其格式?

标签: c#jsonjson.net

解决方案


推荐阅读