JSON 已经成为当前主流交互格式, 如何在C#中使用 Json.Net 对Json文本进行 增删改查呢?见如下代码
#region Create (从零创建) public static string CreateFromZero() { StringBuilder jsonText = new StringBuilder(); StringWriter sw = new StringWriter(jsonText); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.None; writer.WriteStartObject();//{ #region children writer.WritePropertyName("children"); writer.WriteStartArray();//[ writer.WriteStartObject();//{ writer.WritePropertyName("children"); writer.WriteStartArray();//[ writer.WriteStartObject();//{ writer.WritePropertyName("organizationCode"); writer.WriteValue("grandson"); writer.WritePropertyName("organizationName"); writer.WriteValue("孙子节点"); writer.WriteEndObject();//} writer.WriteEndArray();//] writer.WritePropertyName("organizationCode"); writer.WriteValue("son"); writer.WritePropertyName("organizationName"); writer.WriteValue("子节点"); writer.WriteEndObject();//} writer.WriteEndArray();//] #endregion writer.WritePropertyName("organizationCode"); writer.WriteValue("root"); writer.WritePropertyName("organizationName"); writer.WriteValue("根节点"); writer.WriteEndObject();//} } return jsonText.ToString(); } #endregion #region Delete ,Update (删除指定节点 + 在指定节点前后添加 + 修改节点) public static string OperateNode() { string jsonText = CreateFromZero(); JToken jobject = JObject.Parse(jsonText); #region 新节点 StringBuilder jsonTextNew = new StringBuilder(); StringWriter sw = new StringWriter(jsonTextNew); using (JsonWriter writer = new JsonTextWriter(sw)) { writer.Formatting = Formatting.None; writer.WriteStartObject();//{ writer.WritePropertyName("organizationCode"); writer.WriteValue("newson"); writer.WritePropertyName("organizationName"); writer.WriteValue("新节点"); writer.WriteEndObject();//} } #endregion JToken jobjectNew = JObject.Parse(jsonTextNew.ToString()); string[] field = new string[] { "孙子节点" }; List<JToken> removeNodes = new List<JToken>(); GetRemoveNodes(jobject, field, ref removeNodes); foreach (JToken node in removeNodes) { JToken nodeObj = node.Parent; //nodeObj.Remove(); //删除此节点 //nodeObj.AddAfterSelf(jobjectNew); //在此节点后添加 json 对象 //nodeObj.AddBeforeSelf(jobjectNew);//在此节点前添加 json 对象 nodeObj.Replace(jobjectNew); //修改此节点, 通过替换实现 } return jobject.ToString(); } private static void GetRemoveNodes(JToken token, string[] fields, ref List<JToken> removeNodes) { JContainer container = token as JContainer; if (container == null) return; foreach (JToken el in container.Children()) { JProperty p = el as JProperty; if (p != null && fields.Contains(p.Value.ToString())) { removeNodes.Add(el); } GetRemoveNodes(el, fields, ref removeNodes); } } #endregion #region Retrieve (查询) //官网例子比较好: //http://www.newtonsoft.com/json/help/html/QueryingLINQtoJSON.htm #endregion