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