4.添加
①我们发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面
结果:
②现在我们又发现,Jack公司来了一个新同事Linda
//将json转换为JObject JObject jObj = JObject.Parse(json); JObject linda = new JObject(new JProperty("Name", "Linda"), new JProperty("Age", "23")); jObj["Colleagues"].Last.AddAfterSelf(linda); Console.WriteLine(jObj.ToString());结果:
四.简化查询语句使用函数SelectToken可以简化查询语句,具体:
①利用SelectToken来查询名称
结果:
②利用SelectToken来查询所有同事的名字
JObject jObj = JObject.Parse(json); var names = jObj.SelectToken("Colleagues").Select(p => p["Name"]).ToList(); foreach (var name in names) Console.WriteLine(name.ToString());结果:
③查询最后一名同事的年龄
//将json转换为JObject JObject jObj = JObject.Parse(json); var age = jObj.SelectToken("Colleagues[1].Age"); Console.WriteLine(age.ToString());结果:
FAQ
1.如果Json中的Key是变化的但是结构不变,如何获取所要的内容?
例如: 1 { 2 "trends": 3 { 4 "2013-05-31 14:31": 5 [ 6 {"name":"我不是谁的偶像", 7 "query":"我不是谁的偶像", 8 "amount":"65172", 9 "delta":"1596"}, 10 {"name":"世界无烟日","query":"世界无烟日","amount":"33548","delta":"1105"}, 11 {"name":"最萌身高差","query":"最萌身高差","amount":"32089","delta":"1069"}, 12 {"name":"中国合伙人","query":"中国合伙人","amount":"25634","delta":"2"}, 13 {"name":"exo回归","query":"exo回归","amount":"23275","delta":"321"}, 14 {"name":"新一吻定情","query":"新一吻定情","amount":"21506","delta":"283"}, 15 {"name":"进击的巨人","query":"进击的巨人","amount":"20358","delta":"46"}, 16 {"name":"谁的青春没缺失","query":"谁的青春没缺失","amount":"17441","delta":"581"}, 17 {"name":"我爱幸运七","query":"我爱幸运七","amount":"15051","delta":"255"}, 18 {"name":"母爱10平方","query":"母爱10平方","amount":"14027","delta":"453"} 19 ] 20 }, 21 "as_of":1369981898 22 }其中的"2013-05-31 14:31"是变化的key,如何获取其中的"name","query","amount","delta"等信息呢?
通过Linq可以很简单地做到: