Subversion Repository Public Repository

ChrisCompleteCodeTrunk

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
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
#if !(NET20 || NET35 || NET40 || NETFX_CORE || PORTABLE || PORTABLE40 || DNXCORE50)
using System.Buffers;
#endif
using System.Collections.Generic;
using System.IO;
using System.Text;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Serialization;
#if NETFX_CORE
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
#elif DNXCORE50
using Xunit;
using Test = Xunit.FactAttribute;
using Assert = Newtonsoft.Json.Tests.XUnitAssert;
#else
using NUnit.Framework;

#endif

namespace Newtonsoft.Json.Tests
{
    [TestFixture]
    public class DemoTests : TestFixtureBase
    {
        public class HtmlColor
        {
            public int Red { get; set; }
            public int Green { get; set; }
            public int Blue { get; set; }
        }

        [Test]
        public void JsonConverter()
        {
            HtmlColor red = new HtmlColor
            {
                Red = 255,
                Green = 0,
                Blue = 0
            };

            string json = JsonConvert.SerializeObject(red, new JsonSerializerSettings
            {
                Formatting = Formatting.Indented
            });
            // {
            //   "Red": 255,
            //   "Green": 0,
            //   "Blue": 0
            // }

            json = JsonConvert.SerializeObject(red, new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                Converters = { new HtmlColorConverter() }
            });
            // "#FF0000"

            HtmlColor r2 = JsonConvert.DeserializeObject<HtmlColor>(json, new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                Converters = { new HtmlColorConverter() }
            });
            Assert.AreEqual(255, r2.Red);
            Assert.AreEqual(0, r2.Green);
            Assert.AreEqual(0, r2.Blue);

            Assert.AreEqual(@"""#FF0000""", json);
        }

        public class PersonDemo
        {
            public string Name { get; set; }
            public int Age { get; set; }
            public string Job { get; set; }
        }

        public class Session
        {
            public string Name { get; set; }
            public DateTime Date { get; set; }
        }

        public class HtmlColorConverter : JsonConverter
        {
            public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
            {
                // create hex string from value
                HtmlColor color = (HtmlColor)value;
                string hexString = color.Red.ToString("X2")
                                   + color.Green.ToString("X2")
                                   + color.Blue.ToString("X2");

                // write value to json
                writer.WriteValue("#" + hexString);
            }

            //public override object ReadJson(JsonReader reader, Type objectType,
            //    object existingValue, JsonSerializer serializer)
            //{
            //    throw new NotImplementedException();
            //}

            public override object ReadJson(JsonReader reader, Type objectType,
                object existingValue, JsonSerializer serializer)
            {
                // get hex string
                string hexString = (string)reader.Value;
                hexString = hexString.TrimStart('#');

                // build html color from hex
                return new HtmlColor
                {
                    Red = Convert.ToInt32(hexString.Substring(0, 2), 16),
                    Green = Convert.ToInt32(hexString.Substring(2, 2), 16),
                    Blue = Convert.ToInt32(hexString.Substring(4, 2), 16)
                };
            }

            public override bool CanConvert(Type objectType)
            {
                return objectType == typeof(HtmlColor);
            }
        }

        [Test]
        public void SerializationGuide()
        {
            IList<string> roles = new List<string>
            {
                "User",
                "Admin"
            };

            string roleJson = JsonConvert.SerializeObject(roles, Formatting.Indented);
            // [
            //   "User",
            //   "Admin"
            // ]

            IDictionary<DateTime, int> dailyRegistrations = new Dictionary<DateTime, int>
            {
                { new DateTime(2014, 6, 1), 23 },
                { new DateTime(2014, 6, 2), 50 }
            };

            string regJson = JsonConvert.SerializeObject(dailyRegistrations, Formatting.Indented);
            // {
            //   "2014-06-01T00:00:00": 23,
            //   "2014-06-02T00:00:00": 50
            // }

            City c = new City { Name = "Oslo", Population = 650000 };

            string cityJson = JsonConvert.SerializeObject(c, Formatting.Indented);
            // {
            //   "Name": "Oslo",
            //   "Population": 650000
            // }
        }

        [Test]
        public void SerializationBasics()
        {
            IList<string> roles = new List<string>
            {
                "User",
                "Admin"
            };

            MemoryTraceWriter traceWriter = new MemoryTraceWriter();

            string j = JsonConvert.SerializeObject(roles, new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                TraceWriter = traceWriter
            });

            string trace = traceWriter.ToString();
            // Started serializing System.Collections.Generic.List`1[System.String].
            // Finished serializing System.Collections.Generic.List`1[System.String].
            // Verbose Serialized JSON: 
            // [
            //   "User",
            //   "Admin"
            // ]
        }

        [Test]
        public void SerializationBasics2()
        {
            var s = new Session
            {
                Name = "Serialize All The Things",
                Date = new DateTime(2014, 6, 4, 0, 0, 0, DateTimeKind.Utc)
            };

            string j = JsonConvert.SerializeObject(s, new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                Converters = { new JavaScriptDateTimeConverter() }
            });
            // {
            //   "Name": "Serialize All The Things",
            //   "Date": new Date(1401796800000)
            // }

            StringAssert.AreEqual(@"{
  ""Name"": ""Serialize All The Things"",
  ""Date"": new Date(
    1401840000000
  )
}", j);
        }

        [Test]
        public void DeserializationBasics1()
        {
            string j = @"{
              'Name': 'Serialize All The Things',
              'Date': new Date(1401796800000)
            }";

            var s = JsonConvert.DeserializeObject<Session>(j, new JsonSerializerSettings
            {
                Converters = { new JavaScriptDateTimeConverter() }
            });
            // Name = Serialize All The Things
            // Date = Tuesday, 3 June 2014

            Assert.AreEqual("Serialize All The Things", s.Name);
        }

        [Test]
        public void DeserializationBasics2()
        {
            Session s = new Session();
            s.Date = new DateTime(2014, 6, 4);

            string j = @"{
              'Name': 'Serialize All The Things'
            }";

            JsonConvert.PopulateObject(j, s);
            // Name = Serialize All The Things
            // Date = Tuesday, 3 June 2014
        }

        public class City
        {
            public string Name { get; set; }
            public int Population { get; set; }
        }

        public class Employee
        {
            public string Name { get; set; }
        }

        public class Manager : Employee
        {
            public IList<Employee> Reportees { get; set; }
        }

        [Test]
        public void SerializeReferencesByValue()
        {
            Employee arnie = new Employee { Name = "Arnie Admin" };
            Manager mike = new Manager { Name = "Mike Manager" };
            Manager susan = new Manager { Name = "Susan Supervisor" };

            mike.Reportees = new[] { arnie, susan };
            susan.Reportees = new[] { arnie };

            string json = JsonConvert.SerializeObject(mike, Formatting.Indented);
            // {
            //   "Reportees": [
            //     { 
            //       "Name": "Arnie Admin"
            //     },
            //     {
            //       "Reportees": [
            //         {
            //           "Name": "Arnie Admin"
            //         }
            //       ],
            //       "Name": "Susan Supervisor"
            //     }
            //   ],
            //   "Name": "Mike Manager"
            // }

            StringAssert.AreEqual(@"{
  ""Reportees"": [
    {
      ""Name"": ""Arnie Admin""
    },
    {
      ""Reportees"": [
        {
          ""Name"": ""Arnie Admin""
        }
      ],
      ""Name"": ""Susan Supervisor""
    }
  ],
  ""Name"": ""Mike Manager""
}", json);
        }

        [Test]
        public void SerializeReferencesWithMetadata()
        {
            Employee arnie = new Employee { Name = "Arnie Admin" };
            Manager mike = new Manager { Name = "Mike Manager" };
            Manager susan = new Manager { Name = "Susan Supervisor" };

            mike.Reportees = new[] { arnie, susan };
            susan.Reportees = new[] { arnie };

            string json = JsonConvert.SerializeObject(mike, new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Objects,
                PreserveReferencesHandling = PreserveReferencesHandling.Objects
            });
            // {
            //   "$id": "1",
            //   "$type": "YourNamespace.Manager, YourAssembly",
            //   "Name": "Mike Manager",
            //   "Reportees": [
            //     {
            //       "$id": "2",
            //       "$type": "YourNamespace.Employee, YourAssembly",
            //       "Name": "Arnie Admin"
            //     },
            //     {
            //       "$id": "3",
            //       "$type": "YourNamespace.Manager, YourAssembly",
            //       "Name": "Susan Supervisor",
            //       "Reportees": [
            //         {
            //           "$ref": "2"
            //         }
            //       ]
            //     }
            //   ]
            // }

            StringAssert.AreEqual(@"{
  ""$id"": ""1"",
  ""$type"": ""Newtonsoft.Json.Tests.DemoTests+Manager, Newtonsoft.Json.Tests"",
  ""Reportees"": [
    {
      ""$id"": ""2"",
      ""$type"": ""Newtonsoft.Json.Tests.DemoTests+Employee, Newtonsoft.Json.Tests"",
      ""Name"": ""Arnie Admin""
    },
    {
      ""$id"": ""3"",
      ""$type"": ""Newtonsoft.Json.Tests.DemoTests+Manager, Newtonsoft.Json.Tests"",
      ""Reportees"": [
        {
          ""$ref"": ""2""
        }
      ],
      ""Name"": ""Susan Supervisor""
    }
  ],
  ""Name"": ""Mike Manager""
}", json);
        }

        [Test]
        public void RoundtripTypesAndReferences()
        {
            string json = @"{
  '$id': '1',
  '$type': 'Newtonsoft.Json.Tests.DemoTests+Manager, Newtonsoft.Json.Tests',
  'Reportees': [
    {
      '$id': '2',
      '$type': 'Newtonsoft.Json.Tests.DemoTests+Employee, Newtonsoft.Json.Tests',
      'Name': 'Arnie Admin'
    },
    {
      '$id': '3',
      '$type': 'Newtonsoft.Json.Tests.DemoTests+Manager, Newtonsoft.Json.Tests',
      'Reportees': [
        {
          '$ref': '2'
        }
      ],
      'Name': 'Susan Supervisor'
    }
  ],
  'Name': 'Mike Manager'
}";

            var e = JsonConvert.DeserializeObject<Employee>(json, new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Objects,
                PreserveReferencesHandling = PreserveReferencesHandling.Objects
            });
            // Name = Mike Manager
            // Reportees = Arnie Admin, Susan Supervisor

            Manager mike = (Manager)e;
            Manager susan = (Manager)mike.Reportees[1];

            Object.ReferenceEquals(mike.Reportees[0], susan.Reportees[0]);
            // true

            Assert.IsTrue(ReferenceEquals(mike.Reportees[0], susan.Reportees[0]));
        }

        public class House
        {
            public string StreetAddress { get; set; }
            public DateTime BuildDate { get; set; }
            public int Bedrooms { get; set; }
            public decimal FloorArea { get; set; }
        }

        public class House1
        {
            public string StreetAddress { get; set; }

            [JsonIgnore]
            public int Bedrooms { get; set; }

            [JsonIgnore]
            public decimal FloorArea { get; set; }

            [JsonIgnore]
            public DateTime BuildDate { get; set; }
        }

        [JsonObject(MemberSerialization.OptIn)]
        public class House3
        {
            [JsonProperty]
            public string StreetAddress { get; set; }

            public int Bedrooms { get; set; }
            public decimal FloorArea { get; set; }
            public DateTime BuildDate { get; set; }
        }

        [JsonObject(MemberSerialization.OptIn)]
        public class House2
        {
            [JsonProperty("address")]
            public string StreetAddress { get; set; }

            public int Bedrooms { get; set; }
            public decimal FloorArea { get; set; }
            public DateTime BuildDate { get; set; }
        }

        [JsonObject(MemberSerialization.OptIn)]
        public class House4
        {
            [JsonProperty("address", Order = 2)]
            public string StreetAddress { get; set; }

            public int Bedrooms { get; set; }
            public decimal FloorArea { get; set; }

            [JsonProperty("buildDate", Order = 1)]
            public DateTime BuildDate { get; set; }
        }

        [JsonObject(MemberSerialization.OptIn)]
        public class House5
        {
            [JsonProperty("address", Order = 2)]
            public string StreetAddress { get; set; }

            public int Bedrooms { get; set; }
            public decimal FloorArea { get; set; }

            [JsonProperty("buildDate", Order = 1)]
            [JsonConverter(typeof(JavaScriptDateTimeConverter))]
            public DateTime BuildDate { get; set; }
        }

        [Test]
        public void SerializeAttributes()
        {
            var house = new House3();
            house.StreetAddress = "221B Baker Street";
            house.Bedrooms = 2;
            house.FloorArea = 100m;
            house.BuildDate = new DateTime(1890, 1, 1);

            string json = JsonConvert.SerializeObject(house, Formatting.Indented);
            // {
            //   "StreetAddress": "221B Baker Street",
            //   "Bedrooms": 2,
            //   "FloorArea": 100.0,
            //   "BuildDate": "1890-01-01T00:00:00"
            // }

            // {
            //   "StreetAddress": "221B Baker Street"
            // }

            // {
            //   "address": "221B Baker Street"
            // }

            // {
            //   "buildDate": "1890-01-01T00:00:00",
            //   "address": "221B Baker Street"
            // }

            // {
            //   "buildDate": new Date(-2524568400000),
            //   "address": "221B Baker Street"
            // }
        }

        [Test]
        public void MergeJson()
        {
            JObject o1 = JObject.Parse(@"{
              'FirstName': 'John',
              'LastName': 'Smith',
              'Enabled': false,
              'Roles': [ 'User' ]
            }");
            JObject o2 = JObject.Parse(@"{
              'Enabled': true,
              'Roles': [ 'User', 'Admin' ]
            }");

            o1.Merge(o2, new JsonMergeSettings
            {
                // union arrays together to avoid duplicates
                MergeArrayHandling = MergeArrayHandling.Union
            });

            string json = o1.ToString();
            // {
            //   "FirstName": "John",
            //   "LastName": "Smith",
            //   "Enabled": true,
            //   "Roles": [
            //     "User",
            //     "Admin"
            //   ]
            // }

            StringAssert.AreEqual(@"{
  ""FirstName"": ""John"",
  ""LastName"": ""Smith"",
  ""Enabled"": true,
  ""Roles"": [
    ""User"",
    ""Admin""
  ]
}", json);
        }

#if !(NET20 || NET35 || NET40 || NETFX_CORE || PORTABLE || PORTABLE40 || DNXCORE50)
        [Test]
        public void ArrayPooling()
        {
            IList<int> value;

            JsonSerializer serializer = new JsonSerializer();
            using (JsonTextReader reader = new JsonTextReader(new StringReader(@"[1,2,3,4]")))
            {
                reader.ArrayPool = JsonArrayPool.Instance;

                value = serializer.Deserialize<IList<int>>(reader);
            }

            Assert.AreEqual(4, value.Count);
        }
#endif
    }

#if !(NET20 || NET35 || NET40 || NETFX_CORE || PORTABLE || PORTABLE40 || DNXCORE50)
    public class JsonArrayPool : IArrayPool<char>
    {
        public static readonly JsonArrayPool Instance = new JsonArrayPool();

        public char[] Rent(int minimumLength)
        {
            // use System.Buffers shared pool
            return ArrayPool<char>.Shared.Rent(minimumLength);
        }

        public void Return(char[] array)
        {
            // use System.Buffers shared pool
            ArrayPool<char>.Shared.Return(array);
        }
    }
#endif
}

Commits for ChrisCompleteCodeTrunk/M3Workflow/Libraries/Json90r1/Source/Src/Newtonsoft.Json.Tests/DemoTests.cs

Diff revisions: vs.
Revision Author Commited Message
1 BBDSCHRIS picture BBDSCHRIS Wed 22 Aug, 2018 20:08:03 +0000