~ubuntu-branches/ubuntu/trusty/monodevelop/trusty-proposed

« back to all changes in this revision

Viewing changes to external/Newtonsoft.Json/Src/Newtonsoft.Json.Tests/Documentation/SerializationTests.cs

  • Committer: Package Import Robot
  • Author(s): Jo Shields
  • Date: 2013-05-12 09:46:03 UTC
  • mto: This revision was merged to the branch mainline in revision 29.
  • Revision ID: package-import@ubuntu.com-20130512094603-mad323bzcxvmcam0
Tags: upstream-4.0.5+dfsg
ImportĀ upstreamĀ versionĀ 4.0.5+dfsg

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
ļ»æ#region License
 
2
// Copyright (c) 2007 James Newton-King
 
3
//
 
4
// Permission is hereby granted, free of charge, to any person
 
5
// obtaining a copy of this software and associated documentation
 
6
// files (the "Software"), to deal in the Software without
 
7
// restriction, including without limitation the rights to use,
 
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
 
9
// copies of the Software, and to permit persons to whom the
 
10
// Software is furnished to do so, subject to the following
 
11
// conditions:
 
12
//
 
13
// The above copyright notice and this permission notice shall be
 
14
// included in all copies or substantial portions of the Software.
 
15
//
 
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 
23
// OTHER DEALINGS IN THE SOFTWARE.
 
24
#endregion
 
25
 
 
26
#if !(NET35 || NET20 || PORTABLE)
 
27
using System;
 
28
using System.Collections.Generic;
 
29
using System.ComponentModel;
 
30
using System.Dynamic;
 
31
using System.IO;
 
32
using System.Linq;
 
33
using System.Runtime.Serialization;
 
34
using System.Text;
 
35
using Newtonsoft.Json.Converters;
 
36
using Newtonsoft.Json.Linq;
 
37
#if !NETFX_CORE
 
38
using NUnit.Framework;
 
39
#else
 
40
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
 
41
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
 
42
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
 
43
#endif
 
44
using Newtonsoft.Json.Serialization;
 
45
using Newtonsoft.Json.Tests.TestObjects;
 
46
using Newtonsoft.Json.Utilities;
 
47
using System.Globalization;
 
48
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
 
49
 
 
50
namespace Newtonsoft.Json.Tests.Documentation
 
51
{
 
52
  public class SerializationTests
 
53
  {
 
54
    public void SerializeObject()
 
55
    {
 
56
      #region SerializeObject
 
57
      Product product = new Product();
 
58
 
 
59
      product.Name = "Apple";
 
60
      product.ExpiryDate = new DateTime(2008, 12, 28);
 
61
      product.Price = 3.99M;
 
62
      product.Sizes = new string[] { "Small", "Medium", "Large" };
 
63
 
 
64
      string output = JsonConvert.SerializeObject(product);
 
65
      //{
 
66
      //  "Name": "Apple",
 
67
      //  "ExpiryDate": "2008-12-28T00:00:00",
 
68
      //  "Price": 3.99,
 
69
      //  "Sizes": [
 
70
      //    "Small",
 
71
      //    "Medium",
 
72
      //    "Large"
 
73
      //  ]
 
74
      //}
 
75
 
 
76
      Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);
 
77
      #endregion
 
78
    }
 
79
 
 
80
    public void JsonSerializerToStream()
 
81
    {
 
82
      #region JsonSerializerToStream
 
83
      Product product = new Product();
 
84
      product.ExpiryDate = new DateTime(2008, 12, 28);
 
85
 
 
86
      JsonSerializer serializer = new JsonSerializer();
 
87
      serializer.Converters.Add(new JavaScriptDateTimeConverter());
 
88
      serializer.NullValueHandling = NullValueHandling.Ignore;
 
89
 
 
90
      using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
 
91
      using (JsonWriter writer = new JsonTextWriter(sw))
 
92
      {
 
93
        serializer.Serialize(writer, product);
 
94
        // {"ExpiryDate":new Date(1230375600000),"Price":0}
 
95
      }
 
96
      #endregion
 
97
    }
 
98
 
 
99
    #region SerializationAttributes
 
100
    [JsonObject(MemberSerialization.OptIn)]
 
101
    public class Person
 
102
    {
 
103
      // "John Smith"
 
104
      [JsonProperty]
 
105
      public string Name { get; set; }
 
106
 
 
107
      // "2000-12-15T22:11:03"
 
108
      [JsonProperty]
 
109
      public DateTime BirthDate { get; set; }
 
110
 
 
111
      // new Date(976918263055)
 
112
      [JsonProperty]
 
113
      [JsonConverter(typeof(JavaScriptDateTimeConverter))]
 
114
      public DateTime LastModified { get; set; }
 
115
 
 
116
      // not serialized because mode is opt-in
 
117
      public string Department { get; set; }
 
118
    }
 
119
    #endregion
 
120
 
 
121
    #region SerializationCallbacksObject
 
122
    public class SerializationEventTestObject
 
123
    {
 
124
      // 2222
 
125
      // This member is serialized and deserialized with no change.
 
126
      public int Member1 { get; set; }
 
127
 
 
128
      // The value of this field is set and reset during and 
 
129
      // after serialization.
 
130
      public string Member2 { get; set; }
 
131
 
 
132
      // This field is not serialized. The OnDeserializedAttribute 
 
133
      // is used to set the member value after serialization.
 
134
      [JsonIgnore]
 
135
      public string Member3 { get; set; }
 
136
 
 
137
      // This field is set to null, but populated after deserialization.
 
138
      public string Member4 { get; set; }
 
139
 
 
140
      public SerializationEventTestObject()
 
141
      {
 
142
        Member1 = 11;
 
143
        Member2 = "Hello World!";
 
144
        Member3 = "This is a nonserialized value";
 
145
        Member4 = null;
 
146
      }
 
147
 
 
148
      [OnSerializing]
 
149
      internal void OnSerializingMethod(StreamingContext context)
 
150
      {
 
151
        Member2 = "This value went into the data file during serialization.";
 
152
      }
 
153
 
 
154
      [OnSerialized]
 
155
      internal void OnSerializedMethod(StreamingContext context)
 
156
      {
 
157
        Member2 = "This value was reset after serialization.";
 
158
      }
 
159
 
 
160
      [OnDeserializing]
 
161
      internal void OnDeserializingMethod(StreamingContext context)
 
162
      {
 
163
        Member3 = "This value was set during deserialization";
 
164
      }
 
165
 
 
166
      [OnDeserialized]
 
167
      internal void OnDeserializedMethod(StreamingContext context)
 
168
      {
 
169
        Member4 = "This value was set after deserialization.";
 
170
      }
 
171
    }
 
172
    #endregion
 
173
 
 
174
    public void SerializationCallbacksExample()
 
175
    {
 
176
      #region SerializationCallbacksExample
 
177
      SerializationEventTestObject obj = new SerializationEventTestObject();
 
178
 
 
179
      Console.WriteLine(obj.Member1);
 
180
      // 11
 
181
      Console.WriteLine(obj.Member2);
 
182
      // Hello World!
 
183
      Console.WriteLine(obj.Member3);
 
184
      // This is a nonserialized value
 
185
      Console.WriteLine(obj.Member4);
 
186
      // null
 
187
 
 
188
      string json = JsonConvert.SerializeObject(obj, Formatting.Indented);
 
189
      // {
 
190
      //   "Member1": 11,
 
191
      //   "Member2": "This value went into the data file during serialization.",
 
192
      //   "Member4": null
 
193
      // }
 
194
 
 
195
      Console.WriteLine(obj.Member1);
 
196
      // 11
 
197
      Console.WriteLine(obj.Member2);
 
198
      // This value was reset after serialization.
 
199
      Console.WriteLine(obj.Member3);
 
200
      // This is a nonserialized value
 
201
      Console.WriteLine(obj.Member4);
 
202
      // null
 
203
 
 
204
      obj = JsonConvert.DeserializeObject<SerializationEventTestObject>(json);
 
205
 
 
206
      Console.WriteLine(obj.Member1);
 
207
      // 11
 
208
      Console.WriteLine(obj.Member2);
 
209
      // This value went into the data file during serialization.
 
210
      Console.WriteLine(obj.Member3);
 
211
      // This value was set during deserialization
 
212
      Console.WriteLine(obj.Member4);
 
213
      // This value was set after deserialization.
 
214
      #endregion
 
215
    }
 
216
 
 
217
    public void SerializationErrorHandling()
 
218
    {
 
219
      #region SerializationErrorHandling
 
220
      List<string> errors = new List<string>();
 
221
 
 
222
      List<DateTime> c = JsonConvert.DeserializeObject<List<DateTime>>(@"[
 
223
          '2009-09-09T00:00:00Z',
 
224
          'I am not a date and will error!',
 
225
          [
 
226
            1
 
227
          ],
 
228
          '1977-02-20T00:00:00Z',
 
229
          null,
 
230
          '2000-12-01T00:00:00Z'
 
231
        ]",
 
232
        new JsonSerializerSettings
 
233
        {
 
234
          Error = delegate(object sender, ErrorEventArgs args)
 
235
          {
 
236
            errors.Add(args.ErrorContext.Error.Message);
 
237
            args.ErrorContext.Handled = true;
 
238
          },
 
239
          Converters = { new IsoDateTimeConverter() }
 
240
        });
 
241
 
 
242
      // 2009-09-09T00:00:00Z
 
243
      // 1977-02-20T00:00:00Z
 
244
      // 2000-12-01T00:00:00Z
 
245
 
 
246
      // The string was not recognized as a valid DateTime. There is a unknown word starting at index 0.
 
247
      // Unexpected token parsing date. Expected String, got StartArray.
 
248
      // Cannot convert null value to System.DateTime.
 
249
      #endregion
 
250
    }
 
251
 
 
252
    public void SerializationErrorHandlingWithParent()
 
253
    {
 
254
      #region SerializationErrorHandlingWithParent
 
255
      List<string> errors = new List<string>();
 
256
 
 
257
      JsonSerializer serializer = new JsonSerializer();
 
258
      serializer.Error += delegate(object sender, ErrorEventArgs args)
 
259
      {
 
260
        // only log an error once
 
261
        if (args.CurrentObject == args.ErrorContext.OriginalObject)
 
262
          errors.Add(args.ErrorContext.Error.Message);
 
263
      };
 
264
      #endregion
 
265
    }
 
266
 
 
267
    #region SerializationErrorHandlingAttributeObject
 
268
    public class PersonError
 
269
    {
 
270
      private List<string> _roles;
 
271
 
 
272
      public string Name { get; set; }
 
273
      public int Age { get; set; }
 
274
      public List<string> Roles
 
275
      {
 
276
        get
 
277
        {
 
278
          if (_roles == null)
 
279
            throw new Exception("Roles not loaded!");
 
280
 
 
281
          return _roles;
 
282
        }
 
283
        set { _roles = value; }
 
284
      }
 
285
      public string Title { get; set; }
 
286
 
 
287
      [OnError]
 
288
      internal void OnError(StreamingContext context, ErrorContext errorContext)
 
289
      {
 
290
        errorContext.Handled = true;
 
291
      }
 
292
    }
 
293
    #endregion
 
294
 
 
295
    public void SerializationErrorHandlingAttributeExample()
 
296
    {
 
297
      #region SerializationErrorHandlingAttributeExample
 
298
      PersonError person = new PersonError
 
299
      {
 
300
        Name = "George Michael Bluth",
 
301
        Age = 16,
 
302
        Roles = null,
 
303
        Title = "Mister Manager"
 
304
      };
 
305
 
 
306
      string json = JsonConvert.SerializeObject(person, Formatting.Indented);
 
307
 
 
308
      Console.WriteLine(json);
 
309
      //{
 
310
      //  "Name": "George Michael Bluth",
 
311
      //  "Age": 16,
 
312
      //  "Title": "Mister Manager"
 
313
      //}
 
314
      #endregion
 
315
    }
 
316
 
 
317
    public void PreservingObjectReferencesOff()
 
318
    {
 
319
      #region PreservingObjectReferencesOff
 
320
      Person p = new Person
 
321
      {
 
322
        BirthDate = new DateTime(1980, 12, 23, 0, 0, 0, DateTimeKind.Utc),
 
323
        LastModified = new DateTime(2009, 2, 20, 12, 59, 21, DateTimeKind.Utc),
 
324
        Name = "James"
 
325
      };
 
326
 
 
327
      List<Person> people = new List<Person>();
 
328
      people.Add(p);
 
329
      people.Add(p);
 
330
 
 
331
      string json = JsonConvert.SerializeObject(people, Formatting.Indented);
 
332
      //[
 
333
      //  {
 
334
      //    "Name": "James",
 
335
      //    "BirthDate": "1980-12-23T00:00:00Z",
 
336
      //    "LastModified": "2009-02-20T12:59:21Z"
 
337
      //  },
 
338
      //  {
 
339
      //    "Name": "James",
 
340
      //    "BirthDate": "1980-12-23T00:00:00Z",
 
341
      //    "LastModified": "2009-02-20T12:59:21Z"
 
342
      //  }
 
343
      //]
 
344
      #endregion
 
345
    }
 
346
 
 
347
    public void PreservingObjectReferencesOn()
 
348
    {
 
349
      List<Person> people = new List<Person>();
 
350
 
 
351
      #region PreservingObjectReferencesOn
 
352
      string json = JsonConvert.SerializeObject(people, Formatting.Indented,
 
353
        new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
 
354
 
 
355
      //[
 
356
      //  {
 
357
      //    "$id": "1",
 
358
      //    "Name": "James",
 
359
      //    "BirthDate": "1983-03-08T00:00Z",
 
360
      //    "LastModified": "2012-03-21T05:40Z"
 
361
      //  },
 
362
      //  {
 
363
      //    "$ref": "1"
 
364
      //  }
 
365
      //]
 
366
 
 
367
      List<Person> deserializedPeople = JsonConvert.DeserializeObject<List<Person>>(json,
 
368
        new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
 
369
 
 
370
      Console.WriteLine(deserializedPeople.Count);
 
371
      // 2
 
372
 
 
373
      Person p1 = deserializedPeople[0];
 
374
      Person p2 = deserializedPeople[1];
 
375
 
 
376
      Console.WriteLine(p1.Name);
 
377
      // James
 
378
      Console.WriteLine(p2.Name);
 
379
      // James
 
380
 
 
381
      bool equal = Object.ReferenceEquals(p1, p2);
 
382
      // true
 
383
      #endregion
 
384
    }
 
385
 
 
386
    #region PreservingObjectReferencesAttribute
 
387
    [JsonObject(IsReference = true)]
 
388
    public class EmployeeReference
 
389
    {
 
390
      public string Name { get; set; }
 
391
      public EmployeeReference Manager { get; set; }
 
392
    }
 
393
    #endregion
 
394
 
 
395
    #region CustomCreationConverterObject
 
396
    public interface IPerson
 
397
    {
 
398
      string FirstName { get; set; }
 
399
      string LastName { get; set; }
 
400
      DateTime BirthDate { get; set; }
 
401
    }
 
402
 
 
403
    public class Employee : IPerson
 
404
    {
 
405
      public string FirstName { get; set; }
 
406
      public string LastName { get; set; }
 
407
      public DateTime BirthDate { get; set; }
 
408
 
 
409
      public string Department { get; set; }
 
410
      public string JobTitle { get; set; }
 
411
    }
 
412
 
 
413
    public class PersonConverter : CustomCreationConverter<IPerson>
 
414
    {
 
415
      public override IPerson Create(Type objectType)
 
416
      {
 
417
        return new Employee();
 
418
      }
 
419
    }
 
420
    #endregion
 
421
 
 
422
    public void CustomCreationConverterExample()
 
423
    {
 
424
      string json = null;
 
425
 
 
426
      #region CustomCreationConverterExample
 
427
      //[
 
428
      //  {
 
429
      //    "FirstName": "Maurice",
 
430
      //    "LastName": "Moss",
 
431
      //    "BirthDate": "1981-03-08T00:00Z",
 
432
      //    "Department": "IT",
 
433
      //    "JobTitle": "Support"
 
434
      //  },
 
435
      //  {
 
436
      //    "FirstName": "Jen",
 
437
      //    "LastName": "Barber",
 
438
      //    "BirthDate": "1985-12-10T00:00Z",
 
439
      //    "Department": "IT",
 
440
      //    "JobTitle": "Manager"
 
441
      //  }
 
442
      //]
 
443
 
 
444
      List<IPerson> people = JsonConvert.DeserializeObject<List<IPerson>>(json, new PersonConverter());
 
445
 
 
446
      IPerson person = people[0];
 
447
 
 
448
      Console.WriteLine(person.GetType());
 
449
      // Newtonsoft.Json.Tests.Employee
 
450
 
 
451
      Console.WriteLine(person.FirstName);
 
452
      // Maurice
 
453
 
 
454
      Employee employee = (Employee)person;
 
455
 
 
456
      Console.WriteLine(employee.JobTitle);
 
457
      // Support
 
458
      #endregion
 
459
    }
 
460
 
 
461
    public void ContractResolver()
 
462
    {
 
463
      #region ContractResolver
 
464
      Product product = new Product
 
465
      {
 
466
        ExpiryDate = new DateTime(2010, 12, 20, 18, 1, 0, DateTimeKind.Utc),
 
467
        Name = "Widget",
 
468
        Price = 9.99m,
 
469
        Sizes = new[] { "Small", "Medium", "Large" }
 
470
      };
 
471
 
 
472
      string json =
 
473
        JsonConvert.SerializeObject(
 
474
          product,
 
475
          Formatting.Indented,
 
476
          new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }
 
477
        );
 
478
 
 
479
      //{
 
480
      //  "name": "Widget",
 
481
      //  "expiryDate": "2010-12-20T18:01Z",
 
482
      //  "price": 9.99,
 
483
      //  "sizes": [
 
484
      //    "Small",
 
485
      //    "Medium",
 
486
      //    "Large"
 
487
      //  ]
 
488
      //}
 
489
      #endregion
 
490
    }
 
491
 
 
492
    public void SerializingCollectionsSerializing()
 
493
    {
 
494
      #region SerializingCollectionsSerializing
 
495
      Product p1 = new Product
 
496
      {
 
497
        Name = "Product 1",
 
498
        Price = 99.95m,
 
499
        ExpiryDate = new DateTime(2000, 12, 29, 0, 0, 0, DateTimeKind.Utc),
 
500
      };
 
501
      Product p2 = new Product
 
502
      {
 
503
        Name = "Product 2",
 
504
        Price = 12.50m,
 
505
        ExpiryDate = new DateTime(2009, 7, 31, 0, 0, 0, DateTimeKind.Utc),
 
506
      };
 
507
 
 
508
      List<Product> products = new List<Product>();
 
509
      products.Add(p1);
 
510
      products.Add(p2);
 
511
 
 
512
      string json = JsonConvert.SerializeObject(products, Formatting.Indented);
 
513
      //[
 
514
      //  {
 
515
      //    "Name": "Product 1",
 
516
      //    "ExpiryDate": "2000-12-29T00:00Z",
 
517
      //    "Price": 99.95,
 
518
      //    "Sizes": null
 
519
      //  },
 
520
      //  {
 
521
      //    "Name": "Product 2",
 
522
      //    "ExpiryDate": "2009-07-31T00:00Z",
 
523
      //    "Price": 12.50,
 
524
      //    "Sizes": null
 
525
      //  }
 
526
      //]
 
527
      #endregion
 
528
    }
 
529
 
 
530
    public void SerializingCollectionsDeserializing()
 
531
    {
 
532
      #region SerializingCollectionsDeserializing
 
533
      string json = @"[
 
534
        {
 
535
          'Name': 'Product 1',
 
536
          'ExpiryDate': '2000-12-29T00:00Z',
 
537
          'Price': 99.95,
 
538
          'Sizes': null
 
539
        },
 
540
        {
 
541
          'Name': 'Product 2',
 
542
          'ExpiryDate': '2009-07-31T00:00Z',
 
543
          'Price': 12.50,
 
544
          'Sizes': null
 
545
        }
 
546
      ]";
 
547
 
 
548
      List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
 
549
 
 
550
      Console.WriteLine(products.Count);
 
551
      // 2
 
552
      
 
553
      Product p1 = products[0];
 
554
      
 
555
      Console.WriteLine(p1.Name);
 
556
      // Product 1
 
557
      #endregion
 
558
    }
 
559
 
 
560
    public void SerializingCollectionsDeserializingDictionaries()
 
561
    {
 
562
      #region SerializingCollectionsDeserializingDictionaries
 
563
      string json = @"{""key1"":""value1"",""key2"":""value2""}";
 
564
 
 
565
      Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
 
566
 
 
567
      Console.WriteLine(values.Count);
 
568
      // 2
 
569
 
 
570
      Console.WriteLine(values["key1"]);
 
571
      // value1
 
572
      #endregion
 
573
    }
 
574
 
 
575
    #region SerializingDatesInJson
 
576
    public class LogEntry
 
577
    {
 
578
      public string Details { get; set; }
 
579
      public DateTime LogDate { get; set; }
 
580
    }
 
581
 
 
582
    public void WriteJsonDates()
 
583
    {
 
584
      LogEntry entry = new LogEntry
 
585
      {
 
586
        LogDate = new DateTime(2009, 2, 15, 0, 0, 0, DateTimeKind.Utc),
 
587
        Details = "Application started."
 
588
      };
 
589
 
 
590
      // default as of Json.NET 4.5
 
591
      string isoJson = JsonConvert.SerializeObject(entry);
 
592
      // {"Details":"Application started.","LogDate":"2009-02-15T00:00:00Z"}
 
593
 
 
594
      JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings
 
595
      {
 
596
        DateFormatHandling = DateFormatHandling.MicrosoftDateFormat
 
597
      };
 
598
      string microsoftJson = JsonConvert.SerializeObject(entry, microsoftDateFormatSettings);
 
599
      // {"Details":"Application started.","LogDate":"\/Date(1234656000000)\/"}
 
600
 
 
601
      string javascriptJson = JsonConvert.SerializeObject(entry, new JavaScriptDateTimeConverter());
 
602
      // {"Details":"Application started.","LogDate":new Date(1234656000000)}
 
603
    }
 
604
    #endregion
 
605
 
 
606
    #region ReducingSerializedJsonSizeOptOut
 
607
    public class Car
 
608
    {
 
609
      // included in JSON
 
610
      public string Model { get; set; }
 
611
      public DateTime Year { get; set; }
 
612
      public List<string> Features { get; set; }
 
613
 
 
614
      // ignored
 
615
      [JsonIgnore]
 
616
      public DateTime LastModified { get; set; }
 
617
    }
 
618
    #endregion
 
619
 
 
620
    #region ReducingSerializedJsonSizeOptIn
 
621
    [DataContract]
 
622
    public class Computer
 
623
    {
 
624
      // included in JSON
 
625
      [DataMember]
 
626
      public string Name { get; set; }
 
627
      [DataMember]
 
628
      public decimal SalePrice { get; set; }
 
629
 
 
630
      // ignored
 
631
      public string Manufacture { get; set; }
 
632
      public int StockCount { get; set; }
 
633
      public decimal WholeSalePrice { get; set; }
 
634
      public DateTime NextShipmentDate { get; set; }
 
635
    }
 
636
    #endregion
 
637
 
 
638
    #region ReducingSerializedJsonSizeNullValueHandlingObject
 
639
    public class Movie
 
640
    {
 
641
      public string Name { get; set; }
 
642
      public string Description { get; set; }
 
643
      public string Classification { get; set; }
 
644
      public string Studio { get; set; }
 
645
      public DateTime? ReleaseDate { get; set; }
 
646
      public List<string> ReleaseCountries { get; set; }
 
647
    }
 
648
    #endregion
 
649
 
 
650
    public void ReducingSerializedJsonSizeNullValueHandlingExample()
 
651
    {
 
652
      #region ReducingSerializedJsonSizeNullValueHandlingExample
 
653
      Movie movie = new Movie();
 
654
      movie.Name = "Bad Boys III";
 
655
      movie.Description = "It's no Bad Boys";
 
656
 
 
657
      string included = JsonConvert.SerializeObject(movie,
 
658
        Formatting.Indented,
 
659
        new JsonSerializerSettings { });
 
660
 
 
661
      // {
 
662
      //   "Name": "Bad Boys III",
 
663
      //   "Description": "It's no Bad Boys",
 
664
      //   "Classification": null,
 
665
      //   "Studio": null,
 
666
      //   "ReleaseDate": null,
 
667
      //   "ReleaseCountries": null
 
668
      // }
 
669
 
 
670
      string ignored = JsonConvert.SerializeObject(movie,
 
671
        Formatting.Indented,
 
672
        new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
 
673
 
 
674
      // {
 
675
      //   "Name": "Bad Boys III",
 
676
      //   "Description": "It's no Bad Boys"
 
677
      // }
 
678
      #endregion
 
679
    }
 
680
 
 
681
    #region ReducingSerializedJsonSizeDefaultValueHandlingObject
 
682
    public class Invoice
 
683
    {
 
684
      public string Company { get; set; }
 
685
      public decimal Amount { get; set; }
 
686
 
 
687
      // false is default value of bool
 
688
      public bool Paid { get; set; }
 
689
      // null is default value of nullable
 
690
      public DateTime? PaidDate { get; set; }
 
691
 
 
692
      // customize default values
 
693
      [DefaultValue(30)]
 
694
      public int FollowUpDays { get; set; }
 
695
      [DefaultValue("")]
 
696
      public string FollowUpEmailAddress { get; set; }
 
697
    }
 
698
    #endregion
 
699
 
 
700
    public void ReducingSerializedJsonSizeDefaultValueHandlingExample()
 
701
    {
 
702
      #region ReducingSerializedJsonSizeDefaultValueHandlingExample
 
703
      Invoice invoice = new Invoice
 
704
      {
 
705
        Company = "Acme Ltd.",
 
706
        Amount = 50.0m,
 
707
        Paid = false,
 
708
        FollowUpDays = 30,
 
709
        FollowUpEmailAddress = string.Empty,
 
710
        PaidDate = null
 
711
      };
 
712
 
 
713
      string included = JsonConvert.SerializeObject(invoice,
 
714
        Formatting.Indented,
 
715
        new JsonSerializerSettings { });
 
716
 
 
717
      // {
 
718
      //   "Company": "Acme Ltd.",
 
719
      //   "Amount": 50.0,
 
720
      //   "Paid": false,
 
721
      //   "PaidDate": null,
 
722
      //   "FollowUpDays": 30,
 
723
      //   "FollowUpEmailAddress": ""
 
724
      // }
 
725
 
 
726
      string ignored = JsonConvert.SerializeObject(invoice,
 
727
        Formatting.Indented,
 
728
        new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });
 
729
 
 
730
      // {
 
731
      //   "Company": "Acme Ltd.",
 
732
      //   "Amount": 50.0
 
733
      // }
 
734
      #endregion
 
735
    }
 
736
 
 
737
    #region ReducingSerializedJsonSizeContractResolverObject
 
738
    public class DynamicContractResolver : DefaultContractResolver
 
739
    {
 
740
      private readonly char _startingWithChar;
 
741
      public DynamicContractResolver(char startingWithChar)
 
742
      {
 
743
        _startingWithChar = startingWithChar;
 
744
      }
 
745
 
 
746
      protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
 
747
      {
 
748
        IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization);
 
749
 
 
750
        // only serializer properties that start with the specified character
 
751
        properties =
 
752
          properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList();
 
753
 
 
754
        return properties;
 
755
      }
 
756
    }
 
757
 
 
758
    public class Book
 
759
    {
 
760
      public string BookName { get; set; }
 
761
      public decimal BookPrice { get; set; }
 
762
      public string AuthorName { get; set; }
 
763
      public int AuthorAge { get; set; }
 
764
      public string AuthorCountry { get; set; }
 
765
    }
 
766
    #endregion
 
767
 
 
768
    public void ReducingSerializedJsonSizeContractResolverExample()
 
769
    {
 
770
      #region ReducingSerializedJsonSizeContractResolverExample
 
771
      Book book = new Book
 
772
      {
 
773
        BookName = "The Gathering Storm",
 
774
        BookPrice = 16.19m,
 
775
        AuthorName = "Brandon Sanderson",
 
776
        AuthorAge = 34,
 
777
        AuthorCountry = "United States of America"
 
778
      };
 
779
 
 
780
      string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented,
 
781
        new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') });
 
782
 
 
783
      // {
 
784
      //   "AuthorName": "Brandon Sanderson",
 
785
      //   "AuthorAge": 34,
 
786
      //   "AuthorCountry": "United States of America"
 
787
      // }
 
788
 
 
789
      string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented,
 
790
        new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') });
 
791
 
 
792
      // {
 
793
      //   "BookName": "The Gathering Storm",
 
794
      //   "BookPrice": 16.19
 
795
      // }
 
796
      #endregion
 
797
    }
 
798
 
 
799
    #region SerializingPartialJsonFragmentsObject
 
800
    public class SearchResult
 
801
    {
 
802
      public string Title { get; set; }
 
803
      public string Content { get; set; }
 
804
      public string Url { get; set; }
 
805
    }
 
806
    #endregion
 
807
 
 
808
    public void SerializingPartialJsonFragmentsExample()
 
809
    {
 
810
      #region SerializingPartialJsonFragmentsExample
 
811
      string googleSearchText = @"{
 
812
        'responseData': {
 
813
          'results': [
 
814
            {
 
815
              'GsearchResultClass': 'GwebSearch',
 
816
              'unescapedUrl': 'http://en.wikipedia.org/wiki/Paris_Hilton',
 
817
              'url': 'http://en.wikipedia.org/wiki/Paris_Hilton',
 
818
              'visibleUrl': 'en.wikipedia.org',
 
819
              'cacheUrl': 'http://www.google.com/search?q=cache:TwrPfhd22hYJ:en.wikipedia.org',
 
820
              'title': '<b>Paris Hilton</b> - Wikipedia, the free encyclopedia',
 
821
              'titleNoFormatting': 'Paris Hilton - Wikipedia, the free encyclopedia',
 
822
              'content': '[1] In 2006, she released her debut album...'
 
823
            },
 
824
            {
 
825
              'GsearchResultClass': 'GwebSearch',
 
826
              'unescapedUrl': 'http://www.imdb.com/name/nm0385296/',
 
827
              'url': 'http://www.imdb.com/name/nm0385296/',
 
828
              'visibleUrl': 'www.imdb.com',
 
829
              'cacheUrl': 'http://www.google.com/search?q=cache:1i34KkqnsooJ:www.imdb.com',
 
830
              'title': '<b>Paris Hilton</b>',
 
831
              'titleNoFormatting': 'Paris Hilton',
 
832
              'content': 'Self: Zoolander. Socialite <b>Paris Hilton</b>...'
 
833
            }
 
834
          ],
 
835
          'cursor': {
 
836
            'pages': [
 
837
              {
 
838
                'start': '0',
 
839
                'label': 1
 
840
              },
 
841
              {
 
842
                'start': '4',
 
843
                'label': 2
 
844
              },
 
845
              {
 
846
                'start': '8',
 
847
                'label': 3
 
848
              },
 
849
              {
 
850
                'start': '12',
 
851
                'label': 4
 
852
              }
 
853
            ],
 
854
            'estimatedResultCount': '59600000',
 
855
            'currentPageIndex': 0,
 
856
            'moreResultsUrl': 'http://www.google.com/search?oe=utf8&ie=utf8...'
 
857
          }
 
858
        },
 
859
        'responseDetails': null,
 
860
        'responseStatus': 200
 
861
      }";
 
862
 
 
863
      JObject googleSearch = JObject.Parse(googleSearchText);
 
864
 
 
865
      // get JSON result objects into a list
 
866
      IList<JToken> results = googleSearch["responseData"]["results"].Children().ToList();
 
867
 
 
868
      // serialize JSON results into .NET objects
 
869
      IList<SearchResult> searchResults = new List<SearchResult>();
 
870
      foreach (JToken result in results)
 
871
      {
 
872
        SearchResult searchResult = JsonConvert.DeserializeObject<SearchResult>(result.ToString());
 
873
        searchResults.Add(searchResult);
 
874
      }
 
875
 
 
876
      // Title = <b>Paris Hilton</b> - Wikipedia, the free encyclopedia
 
877
      // Content = [1] In 2006, she released her debut album...
 
878
      // Url = http://en.wikipedia.org/wiki/Paris_Hilton
 
879
 
 
880
      // Title = <b>Paris Hilton</b>
 
881
      // Content = Self: Zoolander. Socialite <b>Paris Hilton</b>...
 
882
      // Url = http://www.imdb.com/name/nm0385296/
 
883
      #endregion
 
884
    }
 
885
 
 
886
    public void SerializeMultidimensionalArrayExample()
 
887
    {
 
888
      string[,] famousCouples = new string[,]
 
889
        {
 
890
          {"Adam", "Eve"},
 
891
          {"Bonnie", "Clyde"},
 
892
          {"Donald", "Daisy"},
 
893
          {"Han", "Leia"}
 
894
        };
 
895
 
 
896
      string json = JsonConvert.SerializeObject(famousCouples, Formatting.Indented);
 
897
      // [
 
898
      //   ["Adam", "Eve"],
 
899
      //   ["Bonnie", "Clyde"],
 
900
      //   ["Donald", "Daisy"],
 
901
      //   ["Han", "Leia"]
 
902
      // ]
 
903
 
 
904
      string[,] deserialized = JsonConvert.DeserializeObject<string[,]>(json);
 
905
 
 
906
      Console.WriteLine(deserialized[3, 0] + ", " + deserialized[3, 1]);
 
907
      // Han, Leia
 
908
    }
 
909
  }
 
910
}
 
911
#endif
 
 
b'\\ No newline at end of file'