假如有這樣一個JSon文件
{
"school":
{
"class": [
{
"id": "高一",
"name": "2班",
"teacher":
{
"yu": "張三",
"sx": "李四",
"yy": "王五"
}}
]
}
}
1.新加一個班級
string JsonPath = "D:\\school.json";
string JsonString = File.ReadAllText(JsonPath, Encoding.UTF8);
JObject jobject = JObject.Parse(JsonString);
JObject newStu = new JObject(
new JProperty("id", 2),
new JProperty("name", "3班"),
new JProperty("teacher", new JObject(
new JProperty("yu", "qwe "),
new JProperty("sx", "qwe"),
new JProperty("yy", "qwe")
)
)
);
jobject["school"]["class"].Last.AddAfterSelf(newStu);
string convertString = Convert.ToString(jobject);
File.WriteAllText(JsonPath, convertString);
2.刪除掉某個班級
jobject["school"]["class"][Index].Remove();
3.修改某個班級的id
jobject["school"]["class"][index]["id"] = "123";
注:需要引入Newtonsoft.Json。