我正在编写一个脚本来自动配置客户端。我希望能够读取一个 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 package (又名 Json.NET)。
关于c# - 在一个Json文件中加入一行Json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51419514/