c# - 在一个Json文件中加入一行Json

标签 c# 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 file

我需要在“名称”下添加它。

最佳答案

最简单的选择是将其视为 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 package (又名 Json.NET)。

关于c# - 在一个Json文件中加入一行Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51419514/

相关文章:

javascript - 从节点返回的 json 中的斜线

c# - 如何在自定义部分的 app.config 中获取智能感知?

c# XML 序列化 - 动态元素名称

c# - 如何模拟嵌套的属性和对象及其功能?

javascript - 如何使用内联 Json 加载 jstree?

python - 将 Pandas DataFrame 转换为 JSON

javascript - 使用 ui-select-match 选择多个条目

asp.net - Dotnetopenauth,从 facebook 范围检索电子邮件

c# - 3d 动画 - WPF 或 XNA

c# - foreach c# 无法转换错误