首页 > 解决方案 > 在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文件

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

标签: c#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.JsonNuGet 包(又名 Json.NET)。


推荐阅读