服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - ASP.NET教程 - Json.net 常用使用小结(推荐)

Json.net 常用使用小结(推荐)

2020-01-13 16:26jingxian ASP.NET教程

下面小编就为大家带来一篇Json.net 常用使用小结(推荐)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

Json.net 常用使用小结(推荐)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
using System;
using System.Linq;
using System.Collections.Generic;
 
namespace microstore
{
  public interface IPerson
  {
    string FirstName
    {
      get;
      set;
    }
    string LastName
    {
      get;
      set;
    }
    DateTime BirthDate
    {
      get;
      set;
    }
  }
  public class Employee : IPerson
  {
    public string FirstName
    {
      get;
      set;
    }
    public string LastName
    {
      get;
      set;
    }
    public DateTime BirthDate
    {
      get;
      set;
    }
 
    public string Department
    {
      get;
      set;
    }
    public string JobTitle
    {
      get;
      set;
    }
  }
  public class PersonConverter : Newtonsoft.Json.Converters.CustomCreationConverter<IPerson>
  {
    //重写abstract class CustomCreationConverter<T>的Create方法
    public override IPerson Create(Type objectType)
    {
      return new Employee();
    }
  }
 
  public partial class testjson : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {
      //if (!IsPostBack)
      //  TestJson();
    }
 
    #region 序列化
    public string TestJsonSerialize()
    {
      Product product = new Product();
      product.Name = "Apple";
      product.Expiry = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");
      product.Price = 3.99M;
      //product.Sizes = new string[] { "Small", "Medium", "Large" };
 
      //string json = Newtonsoft.Json.JsonConvert.SerializeObject(product); //没有缩进输出
      string json = Newtonsoft.Json.JsonConvert.SerializeObject(product, Newtonsoft.Json.Formatting.Indented);
      //string json = Newtonsoft.Json.JsonConvert.SerializeObject(
      //  product,
      //  Newtonsoft.Json.Formatting.Indented,
      //  new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }
      //);
      return string.Format("<p>{0}</p>", json);
    }
    public string TestListJsonSerialize()
    {
      Product product = new Product();
      product.Name = "Apple";
      product.Expiry = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd hh:mm:ss");
      product.Price = 3.99M;
      product.Sizes = new string[] { "Small", "Medium", "Large" };
 
      List<Product> plist = new List<Product>();
      plist.Add(product);
      plist.Add(product);
      string json = Newtonsoft.Json.JsonConvert.SerializeObject(plist, Newtonsoft.Json.Formatting.Indented);
      return string.Format("<p>{0}</p>", json);
    }
    #endregion
 
    #region 反序列化
    public string TestJsonDeserialize()
    {
      string strjson = "{\"Name\":\"Apple\",\"Expiry\":\"2014-05-03 10:20:59\",\"Price\":3.99,\"Sizes\":[\"Small\",\"Medium\",\"Large\"]}";
      Product p = Newtonsoft.Json.JsonConvert.DeserializeObject<Product>(strjson);
 
      string template = @"<p><ul>
                  <li>{0}</li>
                  <li>{1}</li>
                  <li>{2}</li>
                  <li>{3}</li>
                </ul></p>";
 
      return string.Format(template, p.Name, p.Expiry, p.Price.ToString(), string.Join(",", p.Sizes));
    }
    public string TestListJsonDeserialize()
    {
      string strjson = "{\"Name\":\"Apple\",\"Expiry\":\"2014-05-03 10:20:59\",\"Price\":3.99,\"Sizes\":[\"Small\",\"Medium\",\"Large\"]}";
      List<Product> plist = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Product>>(string.Format("[{0},{1}]", strjson, strjson));
 
      string template = @"<p><ul>
                  <li>{0}</li>
                  <li>{1}</li>
                  <li>{2}</li>
                  <li>{3}</li>
                </ul></p>";
 
      System.Text.StringBuilder strb = new System.Text.StringBuilder();
      plist.ForEach(x =>
        strb.AppendLine(
          string.Format(template, x.Name, x.Expiry, x.Price.ToString(), string.Join(",", x.Sizes))
        )
      );
      return strb.ToString();
    }
    #endregion
 
    #region 自定义反序列化
    public string TestListCustomDeserialize()
    {
      string strJson = "[ { \"FirstName\": \"Maurice\", \"LastName\": \"Moss\", \"BirthDate\": \"1981-03-08T00:00Z\", \"Department\": \"IT\", \"JobTitle\": \"Support\" }, { \"FirstName\": \"Jen\", \"LastName\": \"Barber\", \"BirthDate\": \"1985-12-10T00:00Z\", \"Department\": \"IT\", \"JobTitle\": \"Manager\" } ] ";
      List<IPerson> people = Newtonsoft.Json.JsonConvert.DeserializeObject<List<IPerson>>(strJson, new PersonConverter());
      IPerson person = people[0];
 
      string template = @"<p><ul>
                  <li>当前List<IPerson>[x]对象类型:{0}</li>
                  <li>FirstName:{1}</li>
                  <li>LastName:{2}</li>
                  <li>BirthDate:{3}</li>
                  <li>Department:{4}</li>
                  <li>JobTitle:{5}</li>
                </ul></p>";
 
      System.Text.StringBuilder strb = new System.Text.StringBuilder();
      people.ForEach(x =>
        strb.AppendLine(
          string.Format(
            template,
            person.GetType().ToString(),
            x.FirstName,
            x.LastName,
            x.BirthDate.ToString(),
            ((Employee)x).Department,
            ((Employee)x).JobTitle
          )
        )
      );
      return strb.ToString();
    }
    #endregion
 
    #region 反序列化成Dictionary
 
    public string TestDeserialize2Dic()
    {
      //string json = @"{""key1"":""zhangsan"",""key2"":""lisi""}";
      //string json = "{\"key1\":\"zhangsan\",\"key2\":\"lisi\"}";
      string json = "{key1:\"zhangsan\",key2:\"lisi\"}";
      Dictionary<string, string> dic = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
 
      string template = @"<li>key:{0},value:{1}</li>";
      System.Text.StringBuilder strb = new System.Text.StringBuilder();
      strb.Append("Dictionary<string, string>长度" + dic.Count.ToString() + "<ul>");
      dic.AsQueryable().ToList().ForEach(x =>
      {
        strb.AppendLine(string.Format(template, x.Key, x.Value));
      });
      strb.Append("</ul>");
      return strb.ToString();
    }
 
    #endregion
 
    #region NullValueHandling特性
    public class Movie
    {
      public string Name { get; set; }
      public string Description { get; set; }
      public string Classification { get; set; }
      public string Studio { get; set; }
      public DateTime? ReleaseDate { get; set; }
      public List<string> ReleaseCountries { get; set; }
    }
    /// <summary>
    /// 完整序列化输出
    /// </summary>
    public string CommonSerialize()
    {
      Movie movie = new Movie();
      movie.Name = "Bad Boys III";
      movie.Description = "It's no Bad Boys";
 
      string included = Newtonsoft.Json.JsonConvert.SerializeObject(
        movie,
        Newtonsoft.Json.Formatting.Indented, //缩进
        new Newtonsoft.Json.JsonSerializerSettings { }
      );
 
      return included;
    }
    /// <summary>
    /// 忽略空(Null)对象输出
    /// </summary>
    /// <returns></returns>
    public string IgnoredSerialize()
    {
      Movie movie = new Movie();
      movie.Name = "Bad Boys III";
      movie.Description = "It's no Bad Boys";
 
      string included = Newtonsoft.Json.JsonConvert.SerializeObject(
        movie,
        Newtonsoft.Json.Formatting.Indented, //缩进
        new Newtonsoft.Json.JsonSerializerSettings { NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore }
      );
 
      return included;
    }
    #endregion
 
    public class Product
    {
      public string Name { get; set; }
      public string Expiry { get; set; }
      public Decimal Price { get; set; }
      public string[] Sizes { get; set; }
    }
 
    #region DefaultValueHandling默认值
    public class Invoice
    {
      public string Company { get; set; }
      public decimal Amount { get; set; }
 
      // false is default value of bool
      public bool Paid { get; set; }
      // null is default value of nullable
      public DateTime? PaidDate { get; set; }
 
      // customize default values
      [System.ComponentModel.DefaultValue(30)]
      public int FollowUpDays { get; set; }
 
      [System.ComponentModel.DefaultValue("")]
      public string FollowUpEmailAddress { get; set; }
    }
    public void GG()
    {
      Invoice invoice = new Invoice
      {
        Company = "Acme Ltd.",
        Amount = 50.0m,
        Paid = false,
        FollowUpDays = 30,
        FollowUpEmailAddress = string.Empty,
        PaidDate = null
      };
 
      string included = Newtonsoft.Json.JsonConvert.SerializeObject(
        invoice,
        Newtonsoft.Json.Formatting.Indented,
        new Newtonsoft.Json.JsonSerializerSettings { }
      );
      // {
      //  "Company": "Acme Ltd.",
      //  "Amount": 50.0,
      //  "Paid": false,
      //  "PaidDate": null,
      //  "FollowUpDays": 30,
      //  "FollowUpEmailAddress": ""
      // }
 
      string ignored = Newtonsoft.Json.JsonConvert.SerializeObject(
        invoice,
        Newtonsoft.Json.Formatting.Indented,
        new Newtonsoft.Json.JsonSerializerSettings { DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore }
      );
      // {
      //  "Company": "Acme Ltd.",
      //  "Amount": 50.0
      // }
    }
    #endregion
 
    #region JsonIgnoreAttribute and DataMemberAttribute 特性
 
    public string OutIncluded()
    {
      Car car = new Car
      {
        Model = "zhangsan",
        Year = DateTime.Now,
        Features = new List<string> { "aaaa", "bbbb", "cccc" },
        LastModified = DateTime.Now.AddDays(5)
      };
      return Newtonsoft.Json.JsonConvert.SerializeObject(car, Newtonsoft.Json.Formatting.Indented);
    }
    public string OutIncluded2()
    {
      Computer com = new Computer
      {
        Name = "zhangsan",
        SalePrice = 3999m,
        Manufacture = "red",
        StockCount = 5,
        WholeSalePrice = 34m,
        NextShipmentDate = DateTime.Now.AddDays(5)
      };
      return Newtonsoft.Json.JsonConvert.SerializeObject(com, Newtonsoft.Json.Formatting.Indented);
    }
 
    public class Car
    {
      // included in JSON
      public string Model { get; set; }
      public DateTime Year { get; set; }
      public List<string> Features { get; set; }
 
      // ignored
      [Newtonsoft.Json.JsonIgnore]
      public DateTime LastModified { get; set; }
    }
 
    //在nt3.5中需要添加System.Runtime.Serialization.dll引用
    [System.Runtime.Serialization.DataContract]
    public class Computer
    {
      // included in JSON
      [System.Runtime.Serialization.DataMember]
      public string Name { get; set; }
      [System.Runtime.Serialization.DataMember]
      public decimal SalePrice { get; set; }
 
      // ignored
      public string Manufacture { get; set; }
      public int StockCount { get; set; }
      public decimal WholeSalePrice { get; set; }
      public DateTime NextShipmentDate { get; set; }
    }
 
    #endregion
 
    #region IContractResolver特性
    public class Book
    {
      public string BookName { get; set; }
      public decimal BookPrice { get; set; }
      public string AuthorName { get; set; }
      public int AuthorAge { get; set; }
      public string AuthorCountry { get; set; }
    }
    public void KK()
    {
      Book book = new Book
      {
        BookName = "The Gathering Storm",
        BookPrice = 16.19m,
        AuthorName = "Brandon Sanderson",
        AuthorAge = 34,
        AuthorCountry = "United States of America"
      };
      string startingWithA = Newtonsoft.Json.JsonConvert.SerializeObject(
        book, Newtonsoft.Json.Formatting.Indented,
        new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') }
      );
      // {
      //  "AuthorName": "Brandon Sanderson",
      //  "AuthorAge": 34,
      //  "AuthorCountry": "United States of America"
      // }
 
      string startingWithB = Newtonsoft.Json.JsonConvert.SerializeObject(
        book,
        Newtonsoft.Json.Formatting.Indented,
        new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') }
      );
      // {
      //  "BookName": "The Gathering Storm",
      //  "BookPrice": 16.19
      // }
    }
    public class DynamicContractResolver : Newtonsoft.Json.Serialization.DefaultContractResolver
    {
      private readonly char _startingWithChar;
 
      public DynamicContractResolver(char startingWithChar)
      {
        _startingWithChar = startingWithChar;
      }
 
      protected override IList<Newtonsoft.Json.Serialization.JsonProperty> CreateProperties(Type type, Newtonsoft.Json.MemberSerialization memberSerialization)
      {
        IList<Newtonsoft.Json.Serialization.JsonProperty> properties = base.CreateProperties(type, memberSerialization);
 
        // only serializer properties that start with the specified character
        properties =
          properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
 
        return properties;
      }
    }
 
    #endregion
 
    //...
  }
}
 
    #region Serializing Partial JSON Fragment Example
    public class SearchResult
    {
      public string Title { get; set; }
      public string Content { get; set; }
      public string Url { get; set; }
    }
 
    public string SerializingJsonFragment()
    {
      #region
      string googleSearchText = @"{
        'responseData': {
          'results': [{
            'GsearchResultClass': 'GwebSearch',
            'unescapedUrl': 'http://en.wikipedia.org/wiki/Paris_Hilton',
            'url': 'http://en.wikipedia.org/wiki/Paris_Hilton',
            'visibleUrl': 'en.wikipedia.org',
            'cacheUrl': 'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org',
            'title': '<b>Paris Hilton</b> - Wikipedia, the free encyclopedia',
            'titleNoFormatting': 'Paris Hilton - Wikipedia, the free encyclopedia',
            'content': '[1] In 2006, she released her debut album...'
          },
          {
            'GsearchResultClass': 'GwebSearch',
            'unescapedUrl': 'http://www.imdb.com/name/nm0385296/',
            'url': 'http://www.imdb.com/name/nm0385296/',
            'visibleUrl': 'www.imdb.com',
            'cacheUrl': 'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com',
            'title': '<b>Paris Hilton</b>',
            'titleNoFormatting': 'Paris Hilton',
            'content': 'Self: Zoolander. Socialite <b>Paris Hilton</b>...'
          }],
          'cursor': {
            'pages': [{
              'start': '0',
              'label': 1
            },
            {
              'start': '4',
              'label': 2
            },
            {
              'start': '8',
              'label': 3
            },
            {
              'start': '12',
              'label': 4
            }],
            'estimatedResultCount': '59600000',
            'currentPageIndex': 0,
            'moreResultsUrl': 'http://www.google.com/search?oe=utf8&ie=utf8...'
          }
        },
        'responseDetails': null,
        'responseStatus': 200
      }";
      #endregion
 
      Newtonsoft.Json.Linq.JObject googleSearch = Newtonsoft.Json.Linq.JObject.Parse(googleSearchText);
      // get JSON result objects into a list
      List<Newtonsoft.Json.Linq.JToken> listJToken = googleSearch["responseData"]["results"].Children().ToList();
      System.Text.StringBuilder strb = new System.Text.StringBuilder();
      string template = @"<ul>
                  <li>Title:{0}</li>
                  <li>Content: {1}</li>
                  <li>Url:{2}</li>
                </ul>";
      listJToken.ForEach(x =>
      {
        // serialize JSON results into .NET objects
        SearchResult searchResult = Newtonsoft.Json.JsonConvert.DeserializeObject<SearchResult>(x.ToString());
        strb.AppendLine(string.Format(template, searchResult.Title, searchResult.Content, searchResult.Url));
      });
      return strb.ToString();
    }
 
    #endregion
 
    #region ShouldSerialize
    public class CC
    {
      public string Name { get; set; }
      public CC Manager { get; set; }
 
      //http://msdn.microsoft.com/en-us/library/53b8022e.aspx
      public bool ShouldSerializeManager()
      {
        // don't serialize the Manager property if an employee is their own manager
        return (Manager != this);
      }
    }
    public string ShouldSerializeTest()
    {
      //create Employee mike
      CC mike = new CC();
      mike.Name = "Mike Manager";
 
      //create Employee joe
      CC joe = new CC();
      joe.Name = "Joe Employee";
      joe.Manager = mike; //set joe'Manager = mike
 
      // mike is his own manager
      // ShouldSerialize will skip this property
      mike.Manager = mike;
      return Newtonsoft.Json.JsonConvert.SerializeObject(new[] { joe, mike }, Newtonsoft.Json.Formatting.Indented);
    }
    #endregion
 
    //驼峰结构输出(小写打头,后面单词大写)
    public string JJJ()
    {
      Product product = new Product
      {
        Name = "Widget",
        Expiry = DateTime.Now.ToString(),
        Price = 9.99m,
        Sizes = new[] { "Small", "Medium", "Large" }
      };
 
      string json = Newtonsoft.Json.JsonConvert.SerializeObject(
        product,
        Newtonsoft.Json.Formatting.Indented,
        new Newtonsoft.Json.JsonSerializerSettings { ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver() }
      );
      return json;
 
      //{
      // "name": "Widget",
      // "expiryDate": "2010-12-20T18:01Z",
      // "price": 9.99,
      // "sizes": [
      //  "Small",
      //  "Medium",
      //  "Large"
      // ]
      //}
    }
 
    #region ITraceWriter
    public class Staff
    {
      public string Name { get; set; }
      public List<string> Roles { get; set; }
      public DateTime StartDate { get; set; }
    }
    public void KKKK()
    {
      Staff staff = new Staff();
      staff.Name = "Arnie Admin";
      staff.Roles = new List<string> { "Administrator" };
      staff.StartDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc);
 
      Newtonsoft.Json.Serialization.ITraceWriter traceWriter = new Newtonsoft.Json.Serialization.MemoryTraceWriter();
      Newtonsoft.Json.JsonConvert.SerializeObject(
        staff,
        new Newtonsoft.Json.JsonSerializerSettings
        {
          TraceWriter = traceWriter,
          Converters = { new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter() }
        }
      );
 
      Console.WriteLine(traceWriter);
      // 2012-11-11T12:08:42.761 Info Started serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
      // 2012-11-11T12:08:42.785 Info Started serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
      // 2012-11-11T12:08:42.791 Info Finished serializing System.DateTime with converter Newtonsoft.Json.Converters.JavaScriptDateTimeConverter. Path 'StartDate'.
      // 2012-11-11T12:08:42.797 Info Started serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
      // 2012-11-11T12:08:42.798 Info Finished serializing System.Collections.Generic.List`1[System.String]. Path 'Roles'.
      // 2012-11-11T12:08:42.799 Info Finished serializing Newtonsoft.Json.Tests.Serialization.Staff. Path ''.
      // 2013-05-18T21:38:11.255 Verbose Serialized JSON:
      // {
      //  "Name": "Arnie Admin",
      //  "StartDate": new Date(
      //   976623132000
      //  ),
      //  "Roles": [
      //   "Administrator"
      //  ]
      // }
    }
    #endregion
 
    public string TestReadJsonFromFile()
    {
      Linq2Json l2j = new Linq2Json();
      Newtonsoft.Json.Linq.JObject jarray = l2j.GetJObject4();
      return jarray.ToString();
    }
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
 
namespace microstore
{
  public class Linq2Json
  {
    #region GetJObject
 
    //Parsing a JSON Object from text
    public Newtonsoft.Json.Linq.JObject GetJObject()
    {
      string json = @"{
               CPU: 'Intel',
               Drives: [
                'DVD read/writer',
                '500 gigabyte hard drive'
               ]
              }";
      Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.Parse(json);
      return jobject;
    }
 
    /*
     * //example:=>
     *
      Linq2Json l2j = new Linq2Json();
      Newtonsoft.Json.Linq.JObject jobject = l2j.GetJObject2(Server.MapPath("json/Person.json"));
      //return Newtonsoft.Json.JsonConvert.SerializeObject(jobject, Newtonsoft.Json.Formatting.Indented);
      return jobject.ToString();
     */
    //Loading JSON from a file
    public Newtonsoft.Json.Linq.JObject GetJObject2(string jsonPath)
    {
      using (System.IO.StreamReader reader = System.IO.File.OpenText(jsonPath))
      {
        Newtonsoft.Json.Linq.JObject jobject = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.Linq.JToken.ReadFrom(new Newtonsoft.Json.JsonTextReader(reader));
        return jobject;
      }
    }
 
    //Creating JObject
    public Newtonsoft.Json.Linq.JObject GetJObject3()
    {
      List<Post> posts = GetPosts();
      Newtonsoft.Json.Linq.JObject jobject = Newtonsoft.Json.Linq.JObject.FromObject(new
      {
        channel = new
        {
          title = "James Newton-King",
          link = "http://james.newtonking.com",
          description = "James Newton-King's blog.",
          item =
            from p in posts
            orderby p.Title
            select new
            {
              title = p.Title,
              description = p.Description,
              link = p.Link,
              category = p.Category
            }
        }
      });
 
      return jobject;
    }
    /*
      {
        "channel": {
          "title": "James Newton-King",
          "link": "http://james.newtonking.com",
          "description": "James Newton-King's blog.",
          "item": [{
            "title": "jewron",
            "description": "4546fds",
            "link": "http://www.baidu.com",
            "category": "jhgj"
          },
          {
            "title": "jofdsn",
            "description": "mdsfan",
            "link": "http://www.baidu.com",
            "category": "6546"
          },
          {
            "title": "jokjn",
            "description": "m3214an",
            "link": "http://www.baidu.com",
            "category": "hg425"
          },
          {
            "title": "jon",
            "description": "man",
            "link": "http://www.baidu.com",
            "category": "goodman"
          }]
        }
      }
     */
    //Creating JObject
    public Newtonsoft.Json.Linq.JObject GetJObject4()
    {
      List<Post> posts = GetPosts();
      Newtonsoft.Json.Linq.JObject rss = new Newtonsoft.Json.Linq.JObject(
          new Newtonsoft.Json.Linq.JProperty("channel",
            new Newtonsoft.Json.Linq.JObject(
              new Newtonsoft.Json.Linq.JProperty("title", "James Newton-King"),
              new Newtonsoft.Json.Linq.JProperty("link", "http://james.newtonking.com"),
              new Newtonsoft.Json.Linq.JProperty("description", "James Newton-King's blog."),
              new Newtonsoft.Json.Linq.JProperty("item",
                new Newtonsoft.Json.Linq.JArray(
                  from p in posts
                  orderby p.Title
                  select new Newtonsoft.Json.Linq.JObject(
                    new Newtonsoft.Json.Linq.JProperty("title", p.Title),
                    new Newtonsoft.Json.Linq.JProperty("description", p.Description),
                    new Newtonsoft.Json.Linq.JProperty("link", p.Link),
                    new Newtonsoft.Json.Linq.JProperty("category",
                      new Newtonsoft.Json.Linq.JArray(
                        from c in p.Category
                        select new Newtonsoft.Json.Linq.JValue(c)
                      )
                    )
                  )
                )
              )
            )
          )
        );
 
      return rss;
    }
    /*
      {
        "channel": {
          "title": "James Newton-King",
          "link": "http://james.newtonking.com",
          "description": "James Newton-King's blog.",
          "item": [{
            "title": "jewron",
            "description": "4546fds",
            "link": "http://www.baidu.com",
            "category": ["j", "h", "g", "j"]
          },
          {
            "title": "jofdsn",
            "description": "mdsfan",
            "link": "http://www.baidu.com",
            "category": ["6", "5", "4", "6"]
          },
          {
            "title": "jokjn",
            "description": "m3214an",
            "link": "http://www.baidu.com",
            "category": ["h", "g", "4", "2", "5"]
          },
          {
            "title": "jon",
            "description": "man",
            "link": "http://www.baidu.com",
            "category": ["g", "o", "o", "d", "m", "a", "n"]
          }]
        }
      }
     */
 
    public class Post
    {
      public string Title { get; set; }
      public string Description { get; set; }
      public string Link { get; set; }
      public string Category { get; set; }
    }
    private List<Post> GetPosts()
    {
      List<Post> listp = new List<Post>()
      {
        new Post{Title="jon",Description="man",Link="http://www.baidu.com",Category="goodman"},
        new Post{Title="jofdsn",Description="mdsfan",Link="http://www.baidu.com",Category="6546"},
        new Post{Title="jewron",Description="4546fds",Link="http://www.baidu.com",Category="jhgj"},
        new Post{Title="jokjn",Description="m3214an",Link="http://www.baidu.com",Category="hg425"}
      };
      return listp;
    }
 
    #endregion
 
    #region GetJArray
    /*
     * //example:=>
     *
      Linq2Json l2j = new Linq2Json();
      Newtonsoft.Json.Linq.JArray jarray = l2j.GetJArray();
      return Newtonsoft.Json.JsonConvert.SerializeObject(jarray, Newtonsoft.Json.Formatting.Indented);
      //return jarray.ToString();
     */
    //Parsing a JSON Array from text
    public Newtonsoft.Json.Linq.JArray GetJArray()
    {
      string json = @"[
               'Small',
               'Medium',
               'Large'
              ]";
 
      Newtonsoft.Json.Linq.JArray jarray = Newtonsoft.Json.Linq.JArray.Parse(json);
      return jarray;
    }
 
    //Creating JArray
    public Newtonsoft.Json.Linq.JArray GetJArray2()
    {
      Newtonsoft.Json.Linq.JArray array = new Newtonsoft.Json.Linq.JArray();
      Newtonsoft.Json.Linq.JValue text = new Newtonsoft.Json.Linq.JValue("Manual text");
      Newtonsoft.Json.Linq.JValue date = new Newtonsoft.Json.Linq.JValue(new DateTime(2000, 5, 23));
      //add to JArray
      array.Add(text);
      array.Add(date);
 
      return array;
    }
 
    #endregion
 
    //待续...
 
  }
}

测试效果:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="testjson.aspx.cs" Inherits="microstore.testjson" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
  <title></title>
  <style type="text/css">
    body{ font-family:Arial,微软雅黑; font-size:14px;}
    a{ text-decoration:none; color:#333;}
    a:hover{ text-decoration:none; color:#f00;}
  </style>
</head>
<body> 
  <form id="form1" runat="server">
    <h3>序列化对象</h3>
    表现1:<br />
    <%=TestJsonSerialize()%>
    <%=TestListJsonSerialize() %>
    表现2:<br />
    <%=TestListJsonSerialize2() %>
    <hr />
    <h3>反序列化对象</h3>
    <p>单个对象</p>
    <%=TestJsonDeserialize() %>
    <p>多个对象</p>
    <%=TestListJsonDeserialize() %> 
    <p>反序列化成数据字典Dictionary</p>
    <%=TestDeserialize2Dic() %>
    <hr /> 
    <h3>自定义反序列化</h3>
    <%=TestListCustomDeserialize()%>
    <hr />
    <h3>序列化输出的忽略特性</h3>
    NullValueHandling特性忽略=><br />
    <%=CommonSerialize() %><br />
    <%=IgnoredSerialize()%><br /><br />
    属性标记忽略=><br />
    <%=OutIncluded() %><br />
    <%=OutIncluded2() %>
    <hr />
    <h3>Serializing Partial JSON Fragments</h3>
    <%=SerializingJsonFragment() %>
    <hr />
    <h3>ShouldSerialize</h3>
    <%=ShouldSerializeTest() %><br />
    <%=JJJ() %><br /><br />
    <%=TestReadJsonFromFile() %>
  </form>
</body>
</html>

显示:

序列化对象

表现1:

 

?
1
2
3
{ "Name": "Apple", "Expiry": "2014-05-04 02:08:58", "Price": 3.99, "Sizes": null }
 
[ { "Name": "Apple", "Expiry": "2014-05-04 02:08:58", "Price": 3.99, "Sizes": [ "Small", "Medium", "Large" ] }, { "Name": "Apple", "Expiry": "2014-05-04 02:08:58", "Price": 3.99, "Sizes": [ "Small", "Medium", "Large" ] } ]

 表现2:

?
1
[ { "Name": "Apple", "Expiry": "2014-05-04 02:08:58", "Price": 3.99, "Sizes": [ "Small", "Medium", "Large" ] }, { "Name": "Apple", "Expiry": "2014-05-04 02:08:58", "Price": 3.99, "Sizes": [ "Small", "Medium", "Large" ] } ]

反序列化对象

单个对象

•Apple
•2014-05-03 10:20:59
•3.99
•Small,Medium,Large

多个对象

•Apple
•2014-05-03 10:20:59
•3.99
•Small,Medium,Large

•Apple
•2014-05-03 10:20:59
•3.99
•Small,Medium,Large

反序列化成数据字典Dictionary

Dictionary长度2
•key:key1,value:zhangsan
•key:key2,value:lisi

---------------------------------------------------------------

自定义反序列化

•当前List[x]对象类型:microstore.Employee
•FirstName:Maurice
•LastName:Moss
•BirthDate:1981-3-8 0:00:00
•Department:IT
•JobTitle:Support


•当前List[x]对象类型:microstore.Employee
•FirstName:Jen
•LastName:Barber
•BirthDate:1985-12-10 0:00:00
•Department:IT
•JobTitle:Manager

-------------------------------------------------------------

序列化输出的忽略特性
NullValueHandling特性忽略=>
{ "Name": "Bad Boys III", "Description": "It's no Bad Boys", "Classification": null, "Studio": null, "ReleaseDate": null, "ReleaseCountries": null }
{ "Name": "Bad Boys III", "Description": "It's no Bad Boys" }

属性标记忽略=>
{ "Model": "zhangsan", "Year": "2014-05-01T02:08:58.671875+08:00", "Features": [ "aaaa", "bbbb", "cccc" ] }
{ "Name": "zhangsan", "SalePrice": 3999.0 }
-----------------------------------------------------------------

Serializing Partial JSON Fragments
•Title:Paris Hilton - Wikipedia, the free encyclopedia
•Content: [1] In 2006, she released her debut album...
•Url:http://en.wikipedia.org/wiki/Paris_Hilton
•Title:Paris Hilton
•Content: Self: Zoolander. Socialite Paris Hilton...
•Url:http://www.imdb.com/name/nm0385296/

--------------------------------------------------------------------------------

ShouldSerialize
[ { "Name": "Joe Employee", "Manager": { "Name": "Mike Manager" } }, { "Name": "Mike Manager" } ]
{ "name": "Widget", "expiry": "2014-5-1 2:08:58", "price": 9.99, "sizes": [ "Small", "Medium", "Large" ] }

{ "channel": { "title": "James Newton-King", "link": "http://james.newtonking.com", "description": "James Newton-King's blog.", "item": [ { "title": "jewron", "description": "4546fds", "link": "http://www.baidu.com", "category": [ "j", "h", "g", "j" ] }, { "title": "jofdsn", "description": "mdsfan", "link": "http://www.baidu.com", "category": [ "6", "5", "4", "6" ] }, { "title": "jokjn", "description": "m3214an", "link": "http://www.baidu.com", "category": [ "h", "g", "4", "2", "5" ] }, { "title": "jon", "description": "man", "link": "http://www.baidu.com", "category": [ "g", "o", "o", "d", "m", "a", "n" ] } ] } }

以上这篇Json.net 常用使用小结(推荐)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

延伸 · 阅读

精彩推荐