用c# 操作Json

假如有這樣一個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。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章