JSON

Json to JObject转换的使用方法,jsontojobject转换(2)

字号+ 作者:H5之家 来源:H5之家 2017-06-28 12:00 我要评论( )

4.添加 ①我们发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面 //将json转换为JObjectJObject jObj = JObject.Parse(json);jObj["Age"].Parent.AddAfterSelf(new JProperty("Department", "Personnel D

4.添加
①我们发现Jack的信息中少了部门信息,要求我们必须添加在Age的后面

//将json转换为JObject JObject jObj = JObject.Parse(json); jObj["Age"].Parent.AddAfterSelf(new JProperty("Department", "Personnel Department")); Console.WriteLine(jObj.ToString());

结果:

②现在我们又发现,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来查询名称

JObject jObj = JObject.Parse(json); JToken name = jObj.SelectToken("Name"); Console.WriteLine(name.ToString());

结果:

②利用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可以很简单地做到:

var jObj = JObject.Parse(jsonString); var tends = from c in jObj.First.First.First.First.Children() select JsonConvert.DeserializeObject<Trend>(c.ToString()); public class Trend { public string Name { get; set; } public string Query { get; set; } public string Amount { get; set; } public string Delta { get; set; } }

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • json学习必看资料

    json学习必看资料

    2017-06-28 16:02

  • JSON 教程(一)

    JSON 教程(一)

    2017-06-28 11:05

  • C#处理JSON 数据

    C#处理JSON 数据

    2017-06-28 11:00

  • jquery,php之间的ajax关系以及json

    jquery,php之间的ajax关系以及json

    2017-06-28 10:01

网友点评
f