假如有这样一个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。