最近整理了一些C# JSON的处理方法,大致如下:

    1—创建json对象
    2—创建json数组
    3—查询
    4—修改
    5—删除
    6—添加
    7—简化查询
    8—删除列表里的a节点的值为aa的项
    9—json其它用法

    :::info 注意:使用该方法的时候需引用Newtonsoft.Json库文件,请在官网(http://www.newtonsoft.com/json)下载 ::: 以上是整理的一些常用JSON处理方法,后续将继续补充!
    代码如下:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.Linq;
    4. using System.Text;
    5. using System.Threading.Tasks;
    6. using System.IO; //StringReader
    7. using Newtonsoft.Json;
    8. using Newtonsoft.Json.Linq;
    9. using Newtonsoft.Json.Converters;//IsoDateTimeConverter
    10. namespace json1
    11. {
    12. class Program
    13. {
    14. static void Main(string[] args)
    15. {
    16. #region 创建json对象
    17. Console.WriteLine("\n\n1--创建json对象:");
    18. JObject staff = new JObject();
    19. staff.Add(new JProperty("Name", "Jack"));//等价于staff.Add("Name","Jack");
    20. staff.Add(new JProperty("Age", 33));
    21. staff.Add(new JProperty("Department", "Personnel Department"));
    22. staff.Add(new JProperty("Leader", new JObject(new JProperty("Name", "Tom"), new JProperty("Age", 44), new JProperty("Department", "Personnel Department"))));
    23. Console.WriteLine(staff.ToString());
    24. #endregion
    25. #region 创建json数组
    26. Console.WriteLine("\n\n2--创建json数组:");
    27. JArray arr = new JArray();
    28. arr.Add(new JValue(1));
    29. arr.Add(new JValue(2));
    30. arr.Add(new JValue(3));
    31. Console.WriteLine(arr.ToString());
    32. #endregion
    33. #region 查询
    34. Console.WriteLine("\n\n3--查询:");
    35. string json3 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";
    36. //将json转换为JObject
    37. JObject jObj = JObject.Parse(json3);
    38. #region 查询-获取某一员工的年龄
    39. Console.WriteLine("获取某一员工的年龄:");
    40. //通过属性名或者索引来访问,仅仅是自己的属性名,而不是所有的
    41. JToken ageToken = jObj["Age"];
    42. Console.WriteLine("age:" + ageToken.ToString());
    43. #endregion
    44. #region 查询-获取该员工所有同事的姓名
    45. Console.WriteLine("获取该员工所有同事的姓名:");
    46. var names = from staff1 in jObj["Colleagues"].Children()
    47. select (string)staff1["Name"];
    48. //"Children()"可以返回所有数组中的对象
    49. foreach (var name in names)
    50. Console.WriteLine(name);
    51. #endregion
    52. #endregion
    53. #region 修改
    54. Console.WriteLine("\n\n4--修改:");
    55. string json4 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29}] }";
    56. //将json转换为JObject
    57. JObject jObj4 = JObject.Parse(json4);
    58. #region 修改--将jack年龄修改为35
    59. Console.WriteLine("修改--将jack年龄修改为35");
    60. jObj4["Age"] = 35;
    61. //JToken age =
    62. Console.WriteLine(jObj4.ToString());
    63. #endregion
    64. #region 修改--将jack同事tom年龄修改Wie45
    65. Console.WriteLine("\n修改--将jack同事tom年龄修改为45");
    66. JToken colleagues = jObj4["Colleagues"];//JToken 不用实例化
    67. colleagues[0]["Age"] = 45;
    68. jObj4["Colleagues"] = colleagues;//将修改后的赋值给json对象
    69. Console.WriteLine(jObj4.ToString());
    70. #endregion
    71. #endregion
    72. #region 删除
    73. Console.WriteLine("\n\n5--删除:");
    74. string json5 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29},{\"Name\" : \"Jully\",\"Age\":23}] }";
    75. //将json转换为JObject
    76. JObject jObj5 = JObject.Parse(json5);
    77. #region 删除--删除同事Tom
    78. Console.WriteLine("删除--删除同事Tom");
    79. jObj5["Colleagues"][0].Remove();
    80. Console.WriteLine(jObj5.ToString());
    81. #endregion
    82. #region 删除--删除所有同事
    83. Console.WriteLine("\n删除--删除所有同事");
    84. jObj5.Remove("Colleagues");//跟的是属性名称
    85. Console.WriteLine(jObj5.ToString());
    86. #endregion
    87. #endregion
    88. #region 添加
    89. Console.WriteLine("\n\n6--添加:");
    90. string json6 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29},{\"Name\" : \"Jully\",\"Age\":23}] }";
    91. //将json转换为JObject
    92. JObject jObj6 = JObject.Parse(json6);
    93. #region 发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面
    94. Console.WriteLine("发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面");
    95. jObj6["Age"].Parent.AddAfterSelf(new JProperty("Department", "Personnel Department"));
    96. Console.WriteLine(jObj6.ToString());
    97. #endregion
    98. #region 添加一个新同事
    99. Console.WriteLine("\n添加一个新同事");
    100. JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23"));
    101. jObj6["Colleagues"].Last.AddAfterSelf(linda);
    102. Console.WriteLine(jObj6.ToString());
    103. #endregion
    104. #endregion
    105. #region 简化查询
    106. Console.WriteLine("\n\n7--简化查询:");
    107. string json7 = "{\"Name\" : \"Jack\", \"Age\" : 34, \"Colleagues\" : [{\"Name\" : \"Tom\" , \"Age\":44},{\"Name\" : \"Abel\",\"Age\":29},{\"Name\" : \"Jully\",\"Age\":23}] }";
    108. //将json转换为JObject
    109. JObject jObj7 = JObject.Parse(json7);
    110. #region 利用SelectToken来查询名称
    111. Console.WriteLine("简化查询--利用SelectToken来查询名称");
    112. JToken name7 = jObj7.SelectToken("Name");
    113. Console.WriteLine(name7.ToString());
    114. #endregion
    115. #region 简化查询--利用SelectToken来查询所有同事的名字
    116. Console.WriteLine("\n简化查询--利用SelectToken来查询所有同事的名字");
    117. var names7 = jObj7.SelectToken("Colleagues").Select(p => p["Name"]).ToList();
    118. foreach (var theName in names7)
    119. Console.WriteLine(theName.ToString());
    120. #endregion
    121. #region 简化查询--查询最后一名同事的年龄
    122. Console.WriteLine("\n简化查询--查询最后一名同事的年龄");
    123. var age = jObj7.SelectToken("Colleagues[2].Age");
    124. Console.WriteLine(age.ToString());
    125. #endregion
    126. #endregion
    127. #region 删除列表里a节点的值为aa的项
    128. Console.WriteLine("\n\n8--删除列表里的a节点的值为aa的项:");
    129. string jsonText = "[{'a':'aaa','b':'bbb','c':'ccc'},{'a':'aa','b':'bb','c':'cc'}]";
    130. var mJObj8 = JArray.Parse(jsonText);
    131. string str1 = mJObj8.ToString();
    132. Console.WriteLine("before delete:\n" + str1);
    133. IList<JToken> delList = new List<JToken>(); //存储需要删除的项
    134. foreach (var ss in mJObj8) //查找某个字段与值
    135. {
    136. if (((JObject)ss)["a"].ToString() == "aa")
    137. delList.Add(ss);
    138. }
    139. foreach (var item in delList) //移除mJObj 在delList 里的项
    140. {
    141. mJObj8.Remove(item);
    142. }
    143. string str2 = mJObj8.ToString();
    144. Console.WriteLine("after delete:\n" + str2);
    145. #endregion
    146. #region json其它用法
    147. Console.WriteLine("\n\n9--json其它用法:");
    148. string jsonStr9_1 = @"
    149. [{'Languages':['C#','Java'],'Name':'李志伟','Sex':true},
    150. {'Languages':['C#','C++'],'Name':'Coder2','Sex':false},
    151. {'Languages':['C#','C++','C','Java'],'Name':'Coder3','Sex':true}]";
    152. Console.WriteLine(jsonStr9_1);
    153. #region 使用JsonTextReader类进行只进读取(不常用)
    154. Console.WriteLine("\n9_1--使用JsonTextReader类进行只进读取:");
    155. JsonTextReader json1 = new JsonTextReader(new StringReader(jsonStr9_1));
    156. while (json1.Read())
    157. {
    158. Console.WriteLine(json1.Value + "--" + json1.TokenType + "--" + json1.ValueType);
    159. }
    160. #endregion
    161. #region 使用JArray、JObject、JToken进行读取(常用)
    162. Console.WriteLine("\n9_2--使用JArray、JObject、JToken进行读取:");
    163. string jsonStr9_2 = @"
    164. [{'Languages':['C#','Java'],'Name':'李志伟','Sex':true},
    165. {'Languages':['C#','C++'],'Name':'Coder2','Sex':false},
    166. {'Languages':['C#','C++','C','Java'],'Name':'Coder3','Sex':true}]";
    167. var Jobj = JArray.Parse(jsonStr9_2);
    168. string mystr1 = Jobj.ToString();
    169. Console.WriteLine("this json:\n" + mystr1);
    170. JArray ja = (JArray)JsonConvert.DeserializeObject(jsonStr9_2);
    171. foreach (JToken jt in ja)
    172. {
    173. JObject jo = (JObject)jt;
    174. JArray temp = (JArray)jo["Languages"];
    175. foreach (JToken token in temp)
    176. {
    177. Console.Write(token + " ");
    178. }
    179. Console.WriteLine("\t" + jo["Name"] + "\t" + jo["Sex"]);
    180. }
    181. #endregion
    182. #region Json时间字符串的处理
    183. Console.WriteLine("\nJson9_3--时间字符串的处理:");
    184. DateTime time = DateTime.Now;
    185. //这里使用自定义日期格式
    186. IsoDateTimeConverter timeConverter = new IsoDateTimeConverter();
    187. timeConverter.DateTimeFormat = "北京时间:yyyy-MM-dd HH:mm:ss";
    188. //序列化时间
    189. string JsonStr = JsonConvert.SerializeObject(time, timeConverter);
    190. Console.WriteLine(JsonStr);
    191. //反序列化时间
    192. DateTime time2 = JsonConvert.DeserializeObject<DateTime>(JsonStr, timeConverter);
    193. Console.WriteLine(time2);
    194. Console.WriteLine("\n\n");
    195. #endregion
    196. #endregion
    197. }
    198. }
    199. }