读,删,修改JSON
string jsonPath = System.Windows.Forms.Application.StartupPath + "\Data\probeData.json"; string jsonString = File.ReadAllText(jsonPath); JObject obj; if (jsonString.Trim() == "") obj = new JObject(); else obj = JObject.Parse(jsonString); JObject jArray = new JObject(); JObject newObj = new JObject( new JProperty("name", "5L64-0.8x10-C18"), new JProperty("custom", 1.1), new JProperty("freq", 2.1) ); JObject newObj2 = new JObject( new JProperty("name", "5L64-0.8x10-C18"), new JProperty("custom", 1.3), new JProperty("freq", 2.2) ); jArray.Add("aaa4", newObj); jArray.Add("aaa6", newObj2); obj.Add("probe", jArray); //--------------------删除-------------------- //JObject tokeselect = obj.SelectToken("probe") as JObject; //JObject tokeselect2 = tokeselect.SelectToken("aaa4") as JObject; ////tokeselect.Remove("aaa4"); //tokeselect2.Remove("name"); //--------------------删除-------------------- //--------------------修改-------------------- obj["probe"]["aaa4"]["name"] = "ccc123"; jsonString = Convert.ToString(obj); System.Diagnostics.Trace.WriteLine(jsonString);
遍历JSON
string jsonPath = System.Windows.Forms.Application.StartupPath + "\global\probe.json"; bool isExist = FileHelper.IsExistFile(jsonPath); JObject JObj; if (isExist) { string jsonString = File.ReadAllText(jsonPath); if (jsonString.Trim() == "") JObj = new JObject(); else JObj = JObject.Parse(jsonString); string str = JObj["probe"].ToString(); //JArray jar = JArray.Parse(str); //for (int i = 0; i < jar.Count; i++) //{ // JToken jt = JToken.Parse(jar[i].ToString()); // foreach (JProperty jp in jt) // { // string name = jp.Name; // } //} JToken jt = JToken.Parse(str); foreach (JProperty jp in jt) { string name = jp.Name; JObject obj2 = JObject.Parse(jp.Value.ToString()); string xxx = obj2["name"].ToString(); } }
JSON文件:
{
"probe": {
"aaa4": {
"name": "ccc123",
"custom": "1",
"freq": "23",
"dist": "33",
"delay": "11",
"date": "2021-08-21"
},
"aaa6": {
"name": "ccc111",
"custom": "2",
"freq": "13",
"dist": "33",
"delay": "31",
"date": "2021-08-22"
}
}
}