当前位置:
首页 > Python基础教程 >
-
C#教程之C# Json.Net解析实例(3)
private void btnDeserializeJsonLinq_Click(object sender, EventArgs e)
237 {
238 string json = @"[
239 {
240 'Title': 'Json.NET is awesome!',
241 'Author': {
242 'Name': 'James Newton-King',
243 'Twitter': '@JamesNK',
244 'Picture': '/jamesnk.png'
245 },
246 'Date': '2013-01-23T19:30:00',
247 'BodyHtml': '<h3>Title!</h3>\r\n<p>Content!</p>'
248 }
249 ]";
250
251 JArray blogPostArray = JArray.Parse(json);
252
253 IList<BlogPost> blogPosts = blogPostArray.Select(p => new BlogPost
254 {
255 Title = (string)p["Title"],
256 AuthorName = (string)p["Author"]["Name"],
257 AuthorTwitter = (string)p["Author"]["Twitter"],
258 PostedDate = (DateTime)p["Date"],
259 Body = HttpUtility.HtmlDecode((string)p["BodyHtml"])
260 }).ToList();
261
262 this.txtJson.Text=(blogPosts[0].Body);
263
264 }
265
266 private void btnSerializeJson_Click(object sender, EventArgs e)
267 {
268 IList<BlogPost> blogPosts = new List<BlogPost>
269 {
270 new BlogPost
271 {
272 Title = "Json.NET is awesome!",
273 AuthorName = "James Newton-King",
274 AuthorTwitter = "JamesNK",
275 PostedDate = new DateTime(2013, 1, 23, 19, 30, 0),
276 Body = @"<h3>Title!</h3>
277 <p>Content!</p>"
278 }
279 };
280
281 JArray blogPostsArray = new JArray(
282 blogPosts.Select(p => new JObject
283 {
284 { "Title", p.Title },
285 {
286 "Author", new JObject
287 {
288 { "Name", p.AuthorName },
289 { "Twitter", p.AuthorTwitter }
290 }
291 },
292 { "Date", p.PostedDate
293 },
294 { "BodyHtml", HttpUtility.HtmlEncode(p.Body) },
295 })
296 );
297
298 this.txtJson.Text=(blogPostsArray.ToString());
299
300 }
301
302 /// <summary>
303 /// 修改Json
304 /// </summary>
305 /// <param name="sender"></param>
306 /// <param name="e"></param>
307 private void btnModifyJson_Click(object sender, EventArgs e)
308 {
309 string json = @"{
310 'channel': {
311 'title': 'Star Wars',
312 'link': 'http://www.starwars.com',
313 'description': 'Star Wars blog.',
314 'obsolete': 'Obsolete value',
315 'item': []
316 }
317 }";
318
319 JObject rss = JObject.Parse(json);
320
321 JObject channel = (JObject)rss["channel"];
322
323 channel["title"] = ((string)channel["title"]).ToUpper();
324 channel["description"] = ((string)channel["description"]).ToUpper();
325
326 channel.Property("obsolete").Remove();
327
328 channel.Property("description").AddAfterSelf(new JProperty("new", "New value"));
329
330 JArray item = (JArray)channel["item"];
331 item.Add("Item 1");
332 item.Add("Item 2");
333
334 this.txtJson.Text=rss.ToString();
335 }
336
337 /// <summary>
338 /// 合并Json
339 /// </summary>
340 /// <param name="sender"></param>
341 /// <param name="e"></param>
342 private void btnMergeJson_Click(object sender, EventArgs e)
343 {
344 JObject o1 = JObject.Parse(@"{
345 'FirstName': 'John',
346 'LastName': 'Smith',
347 'Enabled': false,
348 'Roles': [ 'User' ]
349 }");
350 JObject o2 = JObject.Parse(@"{
351 'Enabled': true,
352 'Roles': [ 'User', 'Admin' ]
353 }");
354
355 o1.Merge(o2, new JsonMergeSettings
356 {
357 // union array values together to avoid duplicates
358 MergeArrayHandling = MergeArrayHandling.Union
359 });
360
361 this.txtJson.Text = o1.ToString();
362 }
363
364 /// <summary>
365 /// 查询Json
366 /// </summary>
367 /// <param name="sender"></param>
368 /// <param name="e"></param>
369 private void btnQueryJson_Click(object sender, EventArgs e)
370 {
371 string json = @"{
372 'channel': {
373 'title': 'James Newton-King',
374 'link': 'http://james.newtonking.com',
375 'description': 'James Newton-King\'s blog.',
376 'item': [
377 {
378 'title': 'Json.NET 1.3 + New license + Now on CodePlex',
379 'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
380 'link': 'http://james.newtonking.com/projects/json-net.aspx',
381 'category': [
382 'Json.NET',
383 'CodePlex'
384 ]
385 },
386 {
387 'title': 'LINQ to JSON beta',
388 'description': 'Annoucing LINQ to JSON',
389 'link': 'http://james.newtonking.com/projects/json-net.aspx',
390 'category': [
391 'Json.NET',
392 'LINQ'
393 ]
394 }
395 ]
396 }
397 }";
398
399 JObject rss = JObject.Parse(json);
400
401 string rssTitle = (string)rss["channel"]["title"];
402
403 Console.WriteLine(rssTitle);
404 // James Newton-King
405
406 string itemTitle = (string)rss["channel"]["item"][0]["title"];
407
408 Console.WriteLine(itemTitle);
409 // Json.NET 1.3 + New license + Now on CodePlex
410
411 JArray categories = (JArray)rss["channel"]["item"][0]["category"];
412
413 Console.WriteLine(categories);
414 // [
415 // "Json.NET",
416 // "CodePlex"
417 // ]
418
419 string[] categoriesText = categories.Select(c => (string)c).ToArray();
420
421 Console.WriteLine(string.Join(", ", categoriesText));
422 // Json.NET, CodePlex
423 }
424
425 private void btnQueryWithLinq_Click(object sender, EventArgs e)
426 {
427 string json = @"{
428 'channel': {
429 'title': 'James Newton-King',
430 'link': 'http://james.newtonking.com',
431 'description': 'James Newton-King\'s blog.',
432 'item': [
433 {
434 'title': 'Json.NET 1.3 + New license + Now on CodePlex',
435 'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
436 'link': 'http://james.newtonking.com/projects/json-net.aspx',
437 'category': [
438 'Json.NET',
439 'CodePlex'
440 ]
441 },
442 {
443 'title': 'LINQ to JSON beta',
444 'description': 'Annoucing LINQ to JSON',
445 'link': 'http://james.newtonking.com/projects/json-net.aspx',
446 'category': [
447 'Json.NET',
448 'LINQ'
449 ]
450 }
451 ]
452 }
453 }";
454
455 JObject rss = JObject.Parse(json);
456
457 var postTitles =
458 from p in rss["channel"]["item"]
459 select (string)p["title"];
460
461 foreach (var item in postTitles)
462 {
463 Console.WriteLine(item);
464 }
465 //LINQ to JSON beta
466 //Json.NET 1.3 + New license + Now on CodePlex
467
468 var categories =
469 from c in rss["channel"]["item"].Children()["category"].Values<string>()
470 group c by c
471 into g
472 orderby g.Count() descending
473 select new { Category = g.Key, Count = g.Count() };
474
475 foreach (var c in categories)
476 {
477 Console.WriteLine(c.Category + " - Count: " + c.Count);
478 }
479 //Json.NET - Count: 2
480 //LINQ - Count: 1
481 //CodePlex - Count: 1
482 }
483
484 private void btnJsonToXml_Click(object sender, EventArgs e)
485 {
486 string json = @"{
487 '@Id': 1,
488 'Email': 'james@example.com',
489 'Active': true,
490 'CreatedDate': '2013-01-20T00:00:00Z',
491 'Roles': [
492 'User',
493 'Admin'
494 ],
495 'Team': {
496 '@Id': 2,
497 'Name': 'Software Developers',
498 'Description': 'Creators of fine software products and services.'
499 }
500 }";
501
502 XNode node = JsonConvert.DeserializeXNode(json, "Root");
503
504 this.txtJson.Text=(node.ToString());
505
506 }
507
508 private void btnXmlToJson_Click(object sender, EventArgs e)
509 {
510 string xml = @"<?xml version='1.0' standalone='no'?>
511 <root>
512 <person id='1'>
513 <name>Alan</name>
514 <url>http://www.google.com</url>
515 </person>
516 <person id='2'>
517 <name>Louis</name>
518 <url>http://www.yahoo.com</url>
519 </person>
520 </root>";
521
522 XmlDocument doc = new XmlDocument();
523 doc.LoadXml(xml);
524
525 string json = JsonConvert.SerializeXmlNode(doc);
526
527 this.txtJson.Text=json;
528 }
529 }
备注:
关于Json的功能有很多,这里只是列举了一些基本的例子,其他的功能需要自己在用到的时候去查阅相关文档了。
关于使用说明文档可以去官网【http://www.newtonsoft.com/json】查看。Samples实例的网址如下:http://www.newtonsoft.com/json/help/html/Samples.htm
--------------------------------------------------------------------------------
作者:Alan.hsiang
出处:http://www.cnblogs.com/hsiang/
本文版权归作者和博客园共有,欢迎转载【点赞】,转载请保留此段声明,且在文章页面明显位置给出原文连接,谢谢。
如要添加联系方式,请备注【博客园】