将一行Json添加到Json文件中

Tix*_*art 1 c# json

我正在编写一个脚本来自动配置客户端.我希望能够读取json文件,并在现有的json中添加一行.

我已经阅读了json文件 - 但是我需要一些帮助来编辑json文件

var pathToJson = Path.Combine(@"C:\" + DownloadConfigFilelocation);
var r = new StreamReader(pathToJson);
var myJson = r.ReadToEnd();
Run Code Online (Sandbox Code Playgroud)

我需要添加这一行

"pageTitle": "Base Client",
Run Code Online (Sandbox Code Playgroud)

到下面的json文件

Json文件

我需要在"名称"下添加它.

Jon*_*eet 7

最简单的选择是将其视为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);
Run Code Online (Sandbox Code Playgroud)

这需要Newtonsoft.JsonNuGet包(又名Json.NET).