c# - 在Json文件中添加一行Json
问题描述
我正在编写一个脚本来自动配置客户端。我希望能够读取一个 json 文件,并在现有的 json 中添加一行。
我已经阅读了 json 文件 - 但是我需要一些帮助来编辑 json 文件
var pathToJson = Path.Combine(@"C:\" + DownloadConfigFilelocation);
var r = new StreamReader(pathToJson);
var myJson = r.ReadToEnd();
我需要添加行
"pageTitle": "Base Client",
到下面的json文件
我需要在“名称”下添加它。
解决方案
最简单的选择是将其视为 JSON:添加一个属性,而不是一行:
// Load the content of the file as a string
string json = File.ReadAllText(pathToJson);
// Parse the JSON to a Newtonsoft.Json.Linq.JObject
JObject obj = JObject.Parse(json);
// Add the property
obj["pageTitle"] = "Base Client";
// Convert back to a JSON string
string newJson = obj.ToString();
// Save the string back to the file
File.WriteAllText(pathToJson, newJson);
这需要Newtonsoft.Json
NuGet 包(又名 Json.NET)。
推荐阅读
- python - 将 pickle 从 Python 传递到 IronPython - cPickle.UnpicklingError: invalid opcode: x
- php - PHP PSR-12 这是示例中的语法错误吗?
- c++ - 在 Visual Studio 2019 中查找或 LINQ C++
- visual-studio-code - 为什么 Node.JS 包必须用 Electron 编译才能在 VSCode 扩展开发中使用它们?
- tensorflow - 如何从 Google 存储桶加载 Tensorflow 冻结图模型?
- c# - 模拟“ASP.NET_SessionId”cookie
- amazon-web-services - 如何拆分 aws:username 策略变量以检查是否已授予写入权限?
- oracle - ORA-01654: 无法在表空间 SYSTEM 00604 中将索引 SYS.I_IDL_UB11 扩展 8。00000 -“递归 SQL 级别 %s 发生错误”
- java - 带有奇偶校验器的正负校验器
- prestashop - Prestashop 提交后返回页面 html