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

« back to all changes in this revision

Viewing changes to external/Newtonsoft.Json/Src/Newtonsoft.Json.Tests/Serialization/TypeNameHandlingTests.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 !PORTABLE
 
27
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
 
28
using System.Dynamic;
 
29
#endif
 
30
using Newtonsoft.Json.Tests.Linq;
 
31
using global::System;
 
32
using global::System.Collections;
 
33
using global::System.Collections.Generic;
 
34
using global::System.Globalization;
 
35
using global::System.Runtime.Serialization.Formatters;
 
36
using global::Newtonsoft.Json.Linq;
 
37
using global::Newtonsoft.Json.Serialization;
 
38
using global::Newtonsoft.Json.Tests.TestObjects;
 
39
#if !NETFX_CORE
 
40
using global::NUnit.Framework;
 
41
#else
 
42
using global::Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
 
43
using TestFixture = global::Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
 
44
using Test = global::Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
 
45
#endif
 
46
using global::Newtonsoft.Json.Utilities;
 
47
using global::System.Net;
 
48
using global::System.Runtime.Serialization;
 
49
using global::System.IO;
 
50
 
 
51
namespace Newtonsoft.Json.Tests.Serialization
 
52
{
 
53
  [TestFixture]
 
54
  public class TypeNameHandlingTests : TestFixtureBase
 
55
  {
 
56
    public class Wrapper
 
57
    {
 
58
      public IList<EmployeeReference> Array { get; set; }
 
59
      public IDictionary<string, EmployeeReference> Dictionary { get; set; }
 
60
    }
 
61
 
 
62
    [Test]
 
63
    public void SerializeWrapper()
 
64
    {
 
65
      Wrapper wrapper = new Wrapper();
 
66
      wrapper.Array = new List<EmployeeReference>
 
67
        {
 
68
          new EmployeeReference()
 
69
        };
 
70
      wrapper.Dictionary = new Dictionary<string, EmployeeReference>
 
71
        {
 
72
          {"First", new EmployeeReference()}
 
73
        };
 
74
 
 
75
      string json = JsonConvert.SerializeObject(wrapper, Formatting.Indented, new JsonSerializerSettings
 
76
        {
 
77
          TypeNameHandling = TypeNameHandling.Auto
 
78
        });
 
79
 
 
80
      Assert.AreEqual(@"{
 
81
  ""Array"": [
 
82
    {
 
83
      ""$id"": ""1"",
 
84
      ""Name"": null,
 
85
      ""Manager"": null
 
86
    }
 
87
  ],
 
88
  ""Dictionary"": {
 
89
    ""First"": {
 
90
      ""$id"": ""2"",
 
91
      ""Name"": null,
 
92
      ""Manager"": null
 
93
    }
 
94
  }
 
95
}", json);
 
96
 
 
97
      Wrapper w2 = JsonConvert.DeserializeObject<Wrapper>(json);
 
98
      CustomAssert.IsInstanceOfType(typeof (List<EmployeeReference>), w2.Array);
 
99
      CustomAssert.IsInstanceOfType(typeof (Dictionary<string, EmployeeReference>), w2.Dictionary);
 
100
    }
 
101
 
 
102
    [Test]
 
103
    public void WriteTypeNameForObjects()
 
104
    {
 
105
      string employeeRef = ReflectionUtils.GetTypeName(typeof (EmployeeReference), FormatterAssemblyStyle.Simple);
 
106
 
 
107
      EmployeeReference employee = new EmployeeReference();
 
108
 
 
109
      string json = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings
 
110
        {
 
111
          TypeNameHandling = TypeNameHandling.Objects
 
112
        });
 
113
 
 
114
      Assert.AreEqual(@"{
 
115
  ""$id"": ""1"",
 
116
  ""$type"": """ + employeeRef + @""",
 
117
  ""Name"": null,
 
118
  ""Manager"": null
 
119
}", json);
 
120
    }
 
121
 
 
122
    [Test]
 
123
    public void DeserializeTypeName()
 
124
    {
 
125
      string employeeRef = ReflectionUtils.GetTypeName(typeof (EmployeeReference), FormatterAssemblyStyle.Simple);
 
126
 
 
127
      string json = @"{
 
128
  ""$id"": ""1"",
 
129
  ""$type"": """ + employeeRef + @""",
 
130
  ""Name"": ""Name!"",
 
131
  ""Manager"": null
 
132
}";
 
133
 
 
134
      object employee = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 
135
        {
 
136
          TypeNameHandling = TypeNameHandling.Objects
 
137
        });
 
138
 
 
139
      CustomAssert.IsInstanceOfType(typeof (EmployeeReference), employee);
 
140
      Assert.AreEqual("Name!", ((EmployeeReference) employee).Name);
 
141
    }
 
142
 
 
143
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
144
    [Test]
 
145
    public void DeserializeTypeNameFromGacAssembly()
 
146
    {
 
147
      string cookieRef = ReflectionUtils.GetTypeName(typeof (Cookie), FormatterAssemblyStyle.Simple);
 
148
 
 
149
      string json = @"{
 
150
  ""$id"": ""1"",
 
151
  ""$type"": """ + cookieRef + @"""
 
152
}";
 
153
 
 
154
      object cookie = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 
155
        {
 
156
          TypeNameHandling = TypeNameHandling.Objects
 
157
        });
 
158
 
 
159
      CustomAssert.IsInstanceOfType(typeof (Cookie), cookie);
 
160
    }
 
161
#endif
 
162
 
 
163
    [Test]
 
164
    public void SerializeGenericObjectListWithTypeName()
 
165
    {
 
166
      string employeeRef = typeof (EmployeeReference).AssemblyQualifiedName;
 
167
      string personRef = typeof (Person).AssemblyQualifiedName;
 
168
 
 
169
      List<object> values = new List<object>
 
170
        {
 
171
          new EmployeeReference
 
172
            {
 
173
              Name = "Bob",
 
174
              Manager = new EmployeeReference {Name = "Frank"}
 
175
            },
 
176
          new Person
 
177
            {
 
178
              Department = "Department",
 
179
              BirthDate = new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc),
 
180
              LastModified = new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc)
 
181
            },
 
182
          "String!",
 
183
          int.MinValue
 
184
        };
 
185
 
 
186
      string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
 
187
        {
 
188
          TypeNameHandling = TypeNameHandling.Objects,
 
189
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 
190
        });
 
191
 
 
192
      Assert.AreEqual(@"[
 
193
  {
 
194
    ""$id"": ""1"",
 
195
    ""$type"": """ + employeeRef + @""",
 
196
    ""Name"": ""Bob"",
 
197
    ""Manager"": {
 
198
      ""$id"": ""2"",
 
199
      ""$type"": """ + employeeRef + @""",
 
200
      ""Name"": ""Frank"",
 
201
      ""Manager"": null
 
202
    }
 
203
  },
 
204
  {
 
205
    ""$type"": """ + personRef + @""",
 
206
    ""Name"": null,
 
207
    ""BirthDate"": ""2000-12-30T00:00:00Z"",
 
208
    ""LastModified"": ""2000-12-30T00:00:00Z""
 
209
  },
 
210
  ""String!"",
 
211
  -2147483648
 
212
]", json);
 
213
    }
 
214
 
 
215
    [Test]
 
216
    public void DeserializeGenericObjectListWithTypeName()
 
217
    {
 
218
      string employeeRef = typeof (EmployeeReference).AssemblyQualifiedName;
 
219
      string personRef = typeof (Person).AssemblyQualifiedName;
 
220
 
 
221
      string json = @"[
 
222
  {
 
223
    ""$id"": ""1"",
 
224
    ""$type"": """ + employeeRef + @""",
 
225
    ""Name"": ""Bob"",
 
226
    ""Manager"": {
 
227
      ""$id"": ""2"",
 
228
      ""$type"": """ + employeeRef + @""",
 
229
      ""Name"": ""Frank"",
 
230
      ""Manager"": null
 
231
    }
 
232
  },
 
233
  {
 
234
    ""$type"": """ + personRef + @""",
 
235
    ""Name"": null,
 
236
    ""BirthDate"": ""\/Date(978134400000)\/"",
 
237
    ""LastModified"": ""\/Date(978134400000)\/""
 
238
  },
 
239
  ""String!"",
 
240
  -2147483648
 
241
]";
 
242
 
 
243
      List<object> values = (List<object>) JsonConvert.DeserializeObject(json, typeof (List<object>), new JsonSerializerSettings
 
244
        {
 
245
          TypeNameHandling = TypeNameHandling.Objects,
 
246
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 
247
        });
 
248
 
 
249
      Assert.AreEqual(4, values.Count);
 
250
 
 
251
      EmployeeReference e = (EmployeeReference) values[0];
 
252
      Person p = (Person) values[1];
 
253
 
 
254
      Assert.AreEqual("Bob", e.Name);
 
255
      Assert.AreEqual("Frank", e.Manager.Name);
 
256
 
 
257
      Assert.AreEqual(null, p.Name);
 
258
      Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.BirthDate);
 
259
      Assert.AreEqual(new DateTime(2000, 12, 30, 0, 0, 0, DateTimeKind.Utc), p.LastModified);
 
260
 
 
261
      Assert.AreEqual("String!", values[2]);
 
262
      Assert.AreEqual((long) int.MinValue, values[3]);
 
263
    }
 
264
 
 
265
    [Test]
 
266
    public void DeserializeWithBadTypeName()
 
267
    {
 
268
      string employeeRef = typeof (EmployeeReference).AssemblyQualifiedName;
 
269
      string personRef = typeof (Person).AssemblyQualifiedName;
 
270
 
 
271
      string json = @"{
 
272
  ""$id"": ""1"",
 
273
  ""$type"": """ + employeeRef + @""",
 
274
  ""Name"": ""Name!"",
 
275
  ""Manager"": null
 
276
}";
 
277
 
 
278
      try
 
279
      {
 
280
        JsonConvert.DeserializeObject(json, typeof (Person), new JsonSerializerSettings
 
281
          {
 
282
            TypeNameHandling = TypeNameHandling.Objects,
 
283
            TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 
284
          });
 
285
      }
 
286
      catch (JsonSerializationException ex)
 
287
      {
 
288
        Assert.IsTrue(ex.Message.StartsWith(@"Type specified in JSON '" + employeeRef + @"' is not compatible with '" + personRef + @"'."));
 
289
      }
 
290
    }
 
291
 
 
292
    [Test]
 
293
    public void DeserializeTypeNameWithNoTypeNameHandling()
 
294
    {
 
295
      string employeeRef = typeof (EmployeeReference).AssemblyQualifiedName;
 
296
 
 
297
      string json = @"{
 
298
  ""$id"": ""1"",
 
299
  ""$type"": """ + employeeRef + @""",
 
300
  ""Name"": ""Name!"",
 
301
  ""Manager"": null
 
302
}";
 
303
 
 
304
      JObject o = (JObject) JsonConvert.DeserializeObject(json);
 
305
 
 
306
      Assert.AreEqual(@"{
 
307
  ""Name"": ""Name!"",
 
308
  ""Manager"": null
 
309
}", o.ToString());
 
310
    }
 
311
 
 
312
    [Test]
 
313
    public void DeserializeTypeNameOnly()
 
314
    {
 
315
      string json = @"{
 
316
  ""$id"": ""1"",
 
317
  ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Employee"",
 
318
  ""Name"": ""Name!"",
 
319
  ""Manager"": null
 
320
}";
 
321
 
 
322
      ExceptionAssert.Throws<JsonSerializationException>(
 
323
        "Type specified in JSON 'Newtonsoft.Json.Tests.TestObjects.Employee' was not resolved. Path '$type', line 3, position 56.",
 
324
        () =>
 
325
          {
 
326
            JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 
327
              {
 
328
                TypeNameHandling = TypeNameHandling.Objects
 
329
              });
 
330
          });
 
331
    }
 
332
 
 
333
    public interface ICorrelatedMessage
 
334
    {
 
335
      string CorrelationId { get; set; }
 
336
    }
 
337
 
 
338
    public class SendHttpRequest : ICorrelatedMessage
 
339
    {
 
340
      public SendHttpRequest()
 
341
      {
 
342
        RequestEncoding = "UTF-8";
 
343
        Method = "GET";
 
344
      }
 
345
 
 
346
      public string Method { get; set; }
 
347
      public Dictionary<string, string> Headers { get; set; }
 
348
      public string Url { get; set; }
 
349
      public Dictionary<string, string> RequestData;
 
350
      public string RequestBodyText { get; set; }
 
351
      public string User { get; set; }
 
352
      public string Passwd { get; set; }
 
353
      public string RequestEncoding { get; set; }
 
354
      public string CorrelationId { get; set; }
 
355
    }
 
356
 
 
357
    [Test]
 
358
    public void DeserializeGenericTypeName()
 
359
    {
 
360
      string typeName = typeof (SendHttpRequest).AssemblyQualifiedName;
 
361
 
 
362
      string json = @"{
 
363
""$type"": """ + typeName + @""",
 
364
""RequestData"": {
 
365
""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"",
 
366
""Id"": ""siedemnaście"",
 
367
""X"": ""323""
 
368
},
 
369
""Method"": ""GET"",
 
370
""Url"": ""http://www.onet.pl"",
 
371
""RequestEncoding"": ""UTF-8"",
 
372
""CorrelationId"": ""xyz""
 
373
}";
 
374
 
 
375
      ICorrelatedMessage message = JsonConvert.DeserializeObject<ICorrelatedMessage>(json, new JsonSerializerSettings
 
376
        {
 
377
          TypeNameHandling = TypeNameHandling.Objects,
 
378
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 
379
        });
 
380
 
 
381
      CustomAssert.IsInstanceOfType(typeof (SendHttpRequest), message);
 
382
 
 
383
      SendHttpRequest request = (SendHttpRequest) message;
 
384
      Assert.AreEqual("xyz", request.CorrelationId);
 
385
      Assert.AreEqual(2, request.RequestData.Count);
 
386
      Assert.AreEqual("siedemnaście", request.RequestData["Id"]);
 
387
    }
 
388
 
 
389
    [Test]
 
390
    public void SerializeObjectWithMultipleGenericLists()
 
391
    {
 
392
      string containerTypeName = typeof (Container).AssemblyQualifiedName;
 
393
      string productListTypeName = typeof (List<Product>).AssemblyQualifiedName;
 
394
 
 
395
      Container container = new Container
 
396
        {
 
397
          In = new List<Product>(),
 
398
          Out = new List<Product>()
 
399
        };
 
400
 
 
401
      string json = JsonConvert.SerializeObject(container, Formatting.Indented,
 
402
                                                new JsonSerializerSettings
 
403
                                                  {
 
404
                                                    NullValueHandling = NullValueHandling.Ignore,
 
405
                                                    TypeNameHandling = TypeNameHandling.All,
 
406
                                                    TypeNameAssemblyFormat = FormatterAssemblyStyle.Full
 
407
                                                  });
 
408
 
 
409
      Assert.AreEqual(@"{
 
410
  ""$type"": """ + containerTypeName + @""",
 
411
  ""In"": {
 
412
    ""$type"": """ + productListTypeName + @""",
 
413
    ""$values"": []
 
414
  },
 
415
  ""Out"": {
 
416
    ""$type"": """ + productListTypeName + @""",
 
417
    ""$values"": []
 
418
  }
 
419
}", json);
 
420
    }
 
421
 
 
422
    public class TypeNameProperty
 
423
    {
 
424
      public string Name { get; set; }
 
425
 
 
426
      [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
 
427
      public object Value { get; set; }
 
428
    }
 
429
 
 
430
    [Test]
 
431
    public void WriteObjectTypeNameForProperty()
 
432
    {
 
433
      string typeNamePropertyRef = ReflectionUtils.GetTypeName(typeof (TypeNameProperty), FormatterAssemblyStyle.Simple);
 
434
 
 
435
      TypeNameProperty typeNameProperty = new TypeNameProperty
 
436
        {
 
437
          Name = "Name!",
 
438
          Value = new TypeNameProperty
 
439
            {
 
440
              Name = "Nested!"
 
441
            }
 
442
        };
 
443
 
 
444
      string json = JsonConvert.SerializeObject(typeNameProperty, Formatting.Indented);
 
445
 
 
446
      Assert.AreEqual(@"{
 
447
  ""Name"": ""Name!"",
 
448
  ""Value"": {
 
449
    ""$type"": """ + typeNamePropertyRef + @""",
 
450
    ""Name"": ""Nested!"",
 
451
    ""Value"": null
 
452
  }
 
453
}", json);
 
454
 
 
455
      TypeNameProperty deserialized = JsonConvert.DeserializeObject<TypeNameProperty>(json);
 
456
      Assert.AreEqual("Name!", deserialized.Name);
 
457
      CustomAssert.IsInstanceOfType(typeof (TypeNameProperty), deserialized.Value);
 
458
 
 
459
      TypeNameProperty nested = (TypeNameProperty) deserialized.Value;
 
460
      Assert.AreEqual("Nested!", nested.Name);
 
461
      Assert.AreEqual(null, nested.Value);
 
462
    }
 
463
 
 
464
    [Test]
 
465
    public void WriteListTypeNameForProperty()
 
466
    {
 
467
      string listRef = ReflectionUtils.GetTypeName(typeof (List<int>), FormatterAssemblyStyle.Simple);
 
468
 
 
469
      TypeNameProperty typeNameProperty = new TypeNameProperty
 
470
        {
 
471
          Name = "Name!",
 
472
          Value = new List<int> {1, 2, 3, 4, 5}
 
473
        };
 
474
 
 
475
      string json = JsonConvert.SerializeObject(typeNameProperty, Formatting.Indented);
 
476
 
 
477
      Assert.AreEqual(@"{
 
478
  ""Name"": ""Name!"",
 
479
  ""Value"": {
 
480
    ""$type"": """ + listRef + @""",
 
481
    ""$values"": [
 
482
      1,
 
483
      2,
 
484
      3,
 
485
      4,
 
486
      5
 
487
    ]
 
488
  }
 
489
}", json);
 
490
 
 
491
      TypeNameProperty deserialized = JsonConvert.DeserializeObject<TypeNameProperty>(json);
 
492
      Assert.AreEqual("Name!", deserialized.Name);
 
493
      CustomAssert.IsInstanceOfType(typeof (List<int>), deserialized.Value);
 
494
 
 
495
      List<int> nested = (List<int>) deserialized.Value;
 
496
      Assert.AreEqual(5, nested.Count);
 
497
      Assert.AreEqual(1, nested[0]);
 
498
      Assert.AreEqual(2, nested[1]);
 
499
      Assert.AreEqual(3, nested[2]);
 
500
      Assert.AreEqual(4, nested[3]);
 
501
      Assert.AreEqual(5, nested[4]);
 
502
    }
 
503
 
 
504
    [Test]
 
505
    public void DeserializeUsingCustomBinder()
 
506
    {
 
507
      string json = @"{
 
508
  ""$id"": ""1"",
 
509
  ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Employee"",
 
510
  ""Name"": ""Name!""
 
511
}";
 
512
 
 
513
      object p = JsonConvert.DeserializeObject(json, null, new JsonSerializerSettings
 
514
        {
 
515
          TypeNameHandling = TypeNameHandling.Objects,
 
516
          Binder = new CustomSerializationBinder()
 
517
        });
 
518
 
 
519
      CustomAssert.IsInstanceOfType(typeof (Person), p);
 
520
 
 
521
      Person person = (Person) p;
 
522
 
 
523
      Assert.AreEqual("Name!", person.Name);
 
524
    }
 
525
 
 
526
    public class CustomSerializationBinder : SerializationBinder
 
527
    {
 
528
      public override Type BindToType(string assemblyName, string typeName)
 
529
      {
 
530
        return typeof (Person);
 
531
      }
 
532
    }
 
533
 
 
534
#if !(NET20 || NET35)
 
535
    [Test]
 
536
    public void SerializeUsingCustomBinder()
 
537
    {
 
538
      TypeNameSerializationBinder binder = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests");
 
539
 
 
540
      IList<object> values = new List<object>
 
541
        {
 
542
          new Customer
 
543
            {
 
544
              Name = "Caroline Customer"
 
545
            },
 
546
          new Purchase
 
547
            {
 
548
              ProductName = "Elbow Grease",
 
549
              Price = 5.99m,
 
550
              Quantity = 1
 
551
            }
 
552
        };
 
553
 
 
554
      string json = JsonConvert.SerializeObject(values, Formatting.Indented, new JsonSerializerSettings
 
555
        {
 
556
          TypeNameHandling = TypeNameHandling.Auto,
 
557
          Binder = binder
 
558
        });
 
559
 
 
560
      //[
 
561
      //  {
 
562
      //    "$type": "Customer",
 
563
      //    "Name": "Caroline Customer"
 
564
      //  },
 
565
      //  {
 
566
      //    "$type": "Purchase",
 
567
      //    "ProductName": "Elbow Grease",
 
568
      //    "Price": 5.99,
 
569
      //    "Quantity": 1
 
570
      //  }
 
571
      //]
 
572
 
 
573
 
 
574
      Assert.AreEqual(@"[
 
575
  {
 
576
    ""$type"": ""Customer"",
 
577
    ""Name"": ""Caroline Customer""
 
578
  },
 
579
  {
 
580
    ""$type"": ""Purchase"",
 
581
    ""ProductName"": ""Elbow Grease"",
 
582
    ""Price"": 5.99,
 
583
    ""Quantity"": 1
 
584
  }
 
585
]", json);
 
586
 
 
587
      IList<object> newValues = JsonConvert.DeserializeObject<IList<object>>(json, new JsonSerializerSettings
 
588
        {
 
589
          TypeNameHandling = TypeNameHandling.Auto,
 
590
          Binder = new TypeNameSerializationBinder("Newtonsoft.Json.Tests.Serialization.{0}, Newtonsoft.Json.Tests")
 
591
        });
 
592
 
 
593
      CustomAssert.IsInstanceOfType(typeof (Customer), newValues[0]);
 
594
      Customer customer = (Customer) newValues[0];
 
595
      Assert.AreEqual("Caroline Customer", customer.Name);
 
596
 
 
597
      CustomAssert.IsInstanceOfType(typeof (Purchase), newValues[1]);
 
598
      Purchase purchase = (Purchase) newValues[1];
 
599
      Assert.AreEqual("Elbow Grease", purchase.ProductName);
 
600
    }
 
601
 
 
602
    public class TypeNameSerializationBinder : SerializationBinder
 
603
    {
 
604
      public string TypeFormat { get; private set; }
 
605
 
 
606
      public TypeNameSerializationBinder(string typeFormat)
 
607
      {
 
608
        TypeFormat = typeFormat;
 
609
      }
 
610
 
 
611
      public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
 
612
      {
 
613
        assemblyName = null;
 
614
        typeName = serializedType.Name;
 
615
      }
 
616
 
 
617
      public override Type BindToType(string assemblyName, string typeName)
 
618
      {
 
619
        string resolvedTypeName = string.Format(TypeFormat, typeName);
 
620
 
 
621
        return Type.GetType(resolvedTypeName, true);
 
622
      }
 
623
    }
 
624
#endif
 
625
 
 
626
    [Test]
 
627
    public void CollectionWithAbstractItems()
 
628
    {
 
629
      HolderClass testObject = new HolderClass();
 
630
      testObject.TestMember = new ContentSubClass("First One");
 
631
      testObject.AnotherTestMember = new Dictionary<int, IList<ContentBaseClass>>();
 
632
      testObject.AnotherTestMember.Add(1, new List<ContentBaseClass>());
 
633
      testObject.AnotherTestMember[1].Add(new ContentSubClass("Second One"));
 
634
      testObject.AThirdTestMember = new ContentSubClass("Third One");
 
635
 
 
636
      JsonSerializer serializingTester = new JsonSerializer();
 
637
      serializingTester.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
 
638
 
 
639
      StringWriter sw = new StringWriter();
 
640
      using (JsonTextWriter jsonWriter = new JsonTextWriter(sw))
 
641
      {
 
642
        jsonWriter.Formatting = Formatting.Indented;
 
643
        serializingTester.TypeNameHandling = TypeNameHandling.Auto;
 
644
        serializingTester.Serialize(jsonWriter, testObject);
 
645
      }
 
646
 
 
647
      string json = sw.ToString();
 
648
 
 
649
      string contentSubClassRef = ReflectionUtils.GetTypeName(typeof (ContentSubClass), FormatterAssemblyStyle.Simple);
 
650
      string dictionaryRef = ReflectionUtils.GetTypeName(typeof (Dictionary<int, IList<ContentBaseClass>>), FormatterAssemblyStyle.Simple);
 
651
      string listRef = ReflectionUtils.GetTypeName(typeof (List<ContentBaseClass>), FormatterAssemblyStyle.Simple);
 
652
 
 
653
      string expected = @"{
 
654
  ""TestMember"": {
 
655
    ""$type"": """ + contentSubClassRef + @""",
 
656
    ""SomeString"": ""First One""
 
657
  },
 
658
  ""AnotherTestMember"": {
 
659
    ""$type"": """ + dictionaryRef + @""",
 
660
    ""1"": [
 
661
      {
 
662
        ""$type"": """ + contentSubClassRef + @""",
 
663
        ""SomeString"": ""Second One""
 
664
      }
 
665
    ]
 
666
  },
 
667
  ""AThirdTestMember"": {
 
668
    ""$type"": """ + contentSubClassRef + @""",
 
669
    ""SomeString"": ""Third One""
 
670
  }
 
671
}";
 
672
 
 
673
      Assert.AreEqual(expected, json);
 
674
 
 
675
      StringReader sr = new StringReader(json);
 
676
 
 
677
      JsonSerializer deserializingTester = new JsonSerializer();
 
678
 
 
679
      HolderClass anotherTestObject;
 
680
 
 
681
      using (JsonTextReader jsonReader = new JsonTextReader(sr))
 
682
      {
 
683
        deserializingTester.TypeNameHandling = TypeNameHandling.Auto;
 
684
 
 
685
        anotherTestObject = deserializingTester.Deserialize<HolderClass>(jsonReader);
 
686
      }
 
687
 
 
688
      Assert.IsNotNull(anotherTestObject);
 
689
      CustomAssert.IsInstanceOfType(typeof (ContentSubClass), anotherTestObject.TestMember);
 
690
      CustomAssert.IsInstanceOfType(typeof (Dictionary<int, IList<ContentBaseClass>>), anotherTestObject.AnotherTestMember);
 
691
      Assert.AreEqual(1, anotherTestObject.AnotherTestMember.Count);
 
692
 
 
693
      IList<ContentBaseClass> list = anotherTestObject.AnotherTestMember[1];
 
694
 
 
695
      CustomAssert.IsInstanceOfType(typeof (List<ContentBaseClass>), list);
 
696
      Assert.AreEqual(1, list.Count);
 
697
      CustomAssert.IsInstanceOfType(typeof (ContentSubClass), list[0]);
 
698
    }
 
699
 
 
700
    [Test]
 
701
    public void WriteObjectTypeNameForPropertyDemo()
 
702
    {
 
703
      Message message = new Message();
 
704
      message.Address = "http://www.google.com";
 
705
      message.Body = new SearchDetails
 
706
        {
 
707
          Query = "Json.NET",
 
708
          Language = "en-us"
 
709
        };
 
710
 
 
711
      string json = JsonConvert.SerializeObject(message, Formatting.Indented);
 
712
      // {
 
713
      //   "Address": "http://www.google.com",
 
714
      //   "Body": {
 
715
      //     "$type": "Newtonsoft.Json.Tests.Serialization.SearchDetails, Newtonsoft.Json.Tests",
 
716
      //     "Query": "Json.NET",
 
717
      //     "Language": "en-us"
 
718
      //   }
 
719
      // }
 
720
 
 
721
      Message deserialized = JsonConvert.DeserializeObject<Message>(json);
 
722
 
 
723
      SearchDetails searchDetails = (SearchDetails) deserialized.Body;
 
724
      // Json.NET
 
725
    }
 
726
 
 
727
    public class UrlStatus
 
728
    {
 
729
      public int Status { get; set; }
 
730
      public string Url { get; set; }
 
731
    }
 
732
 
 
733
 
 
734
    [Test]
 
735
    public void GenericDictionaryObject()
 
736
    {
 
737
      Dictionary<string, object> collection = new Dictionary<string, object>()
 
738
        {
 
739
          {"First", new UrlStatus {Status = 404, Url = @"http://www.bing.com"}},
 
740
          {"Second", new UrlStatus {Status = 400, Url = @"http://www.google.com"}},
 
741
          {
 
742
            "List", new List<UrlStatus>
 
743
              {
 
744
                new UrlStatus {Status = 300, Url = @"http://www.yahoo.com"},
 
745
                new UrlStatus {Status = 200, Url = @"http://www.askjeeves.com"}
 
746
              }
 
747
            }
 
748
        };
 
749
 
 
750
      string json = JsonConvert.SerializeObject(collection, Formatting.Indented, new JsonSerializerSettings
 
751
        {
 
752
          TypeNameHandling = TypeNameHandling.All,
 
753
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
 
754
        });
 
755
 
 
756
      string urlStatusTypeName = ReflectionUtils.GetTypeName(typeof (UrlStatus), FormatterAssemblyStyle.Simple);
 
757
 
 
758
      Assert.AreEqual(@"{
 
759
  ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",
 
760
  ""First"": {
 
761
    ""$type"": """ + urlStatusTypeName + @""",
 
762
    ""Status"": 404,
 
763
    ""Url"": ""http://www.bing.com""
 
764
  },
 
765
  ""Second"": {
 
766
    ""$type"": """ + urlStatusTypeName + @""",
 
767
    ""Status"": 400,
 
768
    ""Url"": ""http://www.google.com""
 
769
  },
 
770
  ""List"": {
 
771
    ""$type"": ""System.Collections.Generic.List`1[[" + urlStatusTypeName + @"]], mscorlib"",
 
772
    ""$values"": [
 
773
      {
 
774
        ""$type"": """ + urlStatusTypeName + @""",
 
775
        ""Status"": 300,
 
776
        ""Url"": ""http://www.yahoo.com""
 
777
      },
 
778
      {
 
779
        ""$type"": """ + urlStatusTypeName + @""",
 
780
        ""Status"": 200,
 
781
        ""Url"": ""http://www.askjeeves.com""
 
782
      }
 
783
    ]
 
784
  }
 
785
}", json);
 
786
 
 
787
      object c = JsonConvert.DeserializeObject(json, new JsonSerializerSettings
 
788
        {
 
789
          TypeNameHandling = TypeNameHandling.All,
 
790
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
 
791
        });
 
792
 
 
793
      CustomAssert.IsInstanceOfType(typeof (Dictionary<string, object>), c);
 
794
 
 
795
      Dictionary<string, object> newCollection = (Dictionary<string, object>) c;
 
796
      Assert.AreEqual(3, newCollection.Count);
 
797
      Assert.AreEqual(@"http://www.bing.com", ((UrlStatus) newCollection["First"]).Url);
 
798
 
 
799
      List<UrlStatus> statues = (List<UrlStatus>) newCollection["List"];
 
800
      Assert.AreEqual(2, statues.Count);
 
801
    }
 
802
 
 
803
 
 
804
    [Test]
 
805
    public void SerializingIEnumerableOfTShouldRetainGenericTypeInfo()
 
806
    {
 
807
      string productClassRef = ReflectionUtils.GetTypeName(typeof (Product[]), FormatterAssemblyStyle.Simple);
 
808
 
 
809
      CustomEnumerable<Product> products = new CustomEnumerable<Product>();
 
810
 
 
811
      string json = JsonConvert.SerializeObject(products, Formatting.Indented, new JsonSerializerSettings {TypeNameHandling = TypeNameHandling.All});
 
812
 
 
813
      Assert.AreEqual(@"{
 
814
  ""$type"": """ + productClassRef + @""",
 
815
  ""$values"": []
 
816
}", json);
 
817
    }
 
818
 
 
819
    public class CustomEnumerable<T> : IEnumerable<T>
 
820
    {
 
821
      //NOTE: a simple linked list
 
822
      private readonly T value;
 
823
      private readonly CustomEnumerable<T> next;
 
824
      private readonly int count;
 
825
 
 
826
      private CustomEnumerable(T value, CustomEnumerable<T> next)
 
827
      {
 
828
        this.value = value;
 
829
        this.next = next;
 
830
        count = this.next.count + 1;
 
831
      }
 
832
 
 
833
      public CustomEnumerable()
 
834
      {
 
835
        count = 0;
 
836
      }
 
837
 
 
838
      public CustomEnumerable<T> AddFirst(T newVal)
 
839
      {
 
840
        return new CustomEnumerable<T>(newVal, this);
 
841
      }
 
842
 
 
843
      public IEnumerator<T> GetEnumerator()
 
844
      {
 
845
        if (count == 0) // last node
 
846
          yield break;
 
847
        yield return value;
 
848
 
 
849
        var nextInLine = next;
 
850
        while (nextInLine != null)
 
851
        {
 
852
          if (nextInLine.count != 0)
 
853
            yield return nextInLine.value;
 
854
          nextInLine = nextInLine.next;
 
855
        }
 
856
      }
 
857
 
 
858
      IEnumerator IEnumerable.GetEnumerator()
 
859
      {
 
860
        return GetEnumerator();
 
861
      }
 
862
    }
 
863
 
 
864
    public class Car
 
865
    {
 
866
      // included in JSON
 
867
      public string Model { get; set; }
 
868
      public DateTime Year { get; set; }
 
869
      public List<string> Features { get; set; }
 
870
      public object[] Objects { get; set; }
 
871
 
 
872
      // ignored
 
873
      [JsonIgnore]
 
874
      public DateTime LastModified { get; set; }
 
875
    }
 
876
 
 
877
    [Test]
 
878
    public void ByteArrays()
 
879
    {
 
880
      Car testerObject = new Car();
 
881
      testerObject.Year = new DateTime(2000, 10, 5, 1, 1, 1, DateTimeKind.Utc);
 
882
      byte[] data = new byte[] {75, 65, 82, 73, 82, 65};
 
883
      testerObject.Objects = new object[] {data, "prueba"};
 
884
 
 
885
      JsonSerializerSettings jsonSettings = new JsonSerializerSettings();
 
886
      jsonSettings.NullValueHandling = NullValueHandling.Ignore;
 
887
      jsonSettings.TypeNameHandling = TypeNameHandling.All;
 
888
 
 
889
      string output = JsonConvert.SerializeObject(testerObject, Formatting.Indented, jsonSettings);
 
890
 
 
891
      string carClassRef = ReflectionUtils.GetTypeName(typeof (Car), FormatterAssemblyStyle.Simple);
 
892
 
 
893
      Assert.AreEqual(output, @"{
 
894
  ""$type"": """ + carClassRef + @""",
 
895
  ""Year"": ""2000-10-05T01:01:01Z"",
 
896
  ""Objects"": {
 
897
    ""$type"": ""System.Object[], mscorlib"",
 
898
    ""$values"": [
 
899
      {
 
900
        ""$type"": ""System.Byte[], mscorlib"",
 
901
        ""$value"": ""S0FSSVJB""
 
902
      },
 
903
      ""prueba""
 
904
    ]
 
905
  }
 
906
}");
 
907
      Car obj = JsonConvert.DeserializeObject<Car>(output, jsonSettings);
 
908
 
 
909
      Assert.IsNotNull(obj);
 
910
 
 
911
      Assert.IsTrue(obj.Objects[0] is byte[]);
 
912
 
 
913
      byte[] d = (byte[]) obj.Objects[0];
 
914
      CollectionAssert.AreEquivalent(data, d);
 
915
    }
 
916
 
 
917
#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE)
 
918
    [Test]
 
919
    public void ISerializableTypeNameHandlingTest()
 
920
    {
 
921
      //Create an instance of our example type
 
922
      IExample e = new Example("Rob");
 
923
 
 
924
      SerializableWrapper w = new SerializableWrapper
 
925
        {
 
926
          Content = e
 
927
        };
 
928
 
 
929
      //Test Binary Serialization Round Trip
 
930
      //This will work find because the Binary Formatter serializes type names
 
931
      //this.TestBinarySerializationRoundTrip(e);
 
932
 
 
933
      //Test Json Serialization
 
934
      //This fails because the JsonSerializer doesn't serialize type names correctly for ISerializable objects
 
935
      //Type Names should be serialized for All, Auto and Object modes
 
936
      this.TestJsonSerializationRoundTrip(w, TypeNameHandling.All);
 
937
      this.TestJsonSerializationRoundTrip(w, TypeNameHandling.Auto);
 
938
      this.TestJsonSerializationRoundTrip(w, TypeNameHandling.Objects);
 
939
    }
 
940
 
 
941
    private void TestJsonSerializationRoundTrip(SerializableWrapper e, TypeNameHandling flag)
 
942
    {
 
943
      Console.WriteLine("Type Name Handling: " + flag.ToString());
 
944
      StringWriter writer = new StringWriter();
 
945
 
 
946
      //Create our serializer and set Type Name Handling appropriately
 
947
      JsonSerializer serializer = new JsonSerializer();
 
948
      serializer.TypeNameHandling = flag;
 
949
 
 
950
      //Do the actual serialization and dump to Console for inspection
 
951
      serializer.Serialize(new JsonTextWriter(writer), e);
 
952
      Console.WriteLine(writer.ToString());
 
953
      Console.WriteLine();
 
954
 
 
955
      //Now try to deserialize
 
956
      //Json.Net will cause an error here as it will try and instantiate
 
957
      //the interface directly because it failed to respect the
 
958
      //TypeNameHandling property on serialization
 
959
      SerializableWrapper f = serializer.Deserialize<SerializableWrapper>(new JsonTextReader(new StringReader(writer.ToString())));
 
960
 
 
961
      //Check Round Trip
 
962
      Assert.AreEqual(e, f, "Objects should be equal after round trip json serialization");
 
963
    }
 
964
#endif
 
965
 
 
966
#if !(NET20 || NET35)
 
967
    [Test]
 
968
    public void SerializationBinderWithFullName()
 
969
    {
 
970
      Message message = new Message
 
971
        {
 
972
          Address = "jamesnk@testtown.com",
 
973
          Body = new Version(1, 2, 3, 4)
 
974
        };
 
975
 
 
976
      string json = JsonConvert.SerializeObject(message, Formatting.Indented, new JsonSerializerSettings
 
977
        {
 
978
          TypeNameHandling = TypeNameHandling.All,
 
979
          TypeNameAssemblyFormat = FormatterAssemblyStyle.Full,
 
980
          Binder = new MetroBinder(),
 
981
          ContractResolver = new DefaultContractResolver
 
982
            {
 
983
#if !(SILVERLIGHT || NETFX_CORE || PORTABLE)
 
984
              IgnoreSerializableAttribute = true
 
985
#endif
 
986
            }
 
987
        });
 
988
 
 
989
      Assert.AreEqual(@"{
 
990
  ""$type"": "":::MESSAGE:::, AssemblyName"",
 
991
  ""Address"": ""jamesnk@testtown.com"",
 
992
  ""Body"": {
 
993
    ""$type"": "":::VERSION:::, AssemblyName"",
 
994
    ""Major"": 1,
 
995
    ""Minor"": 2,
 
996
    ""Build"": 3,
 
997
    ""Revision"": 4,
 
998
    ""MajorRevision"": 0,
 
999
    ""MinorRevision"": 4
 
1000
  }
 
1001
}", json);
 
1002
    }
 
1003
 
 
1004
    public class MetroBinder : SerializationBinder
 
1005
    {
 
1006
      public override Type BindToType(string assemblyName, string typeName)
 
1007
      {
 
1008
        return null;
 
1009
      }
 
1010
 
 
1011
      public override void BindToName(Type serializedType, out string assemblyName, out string typeName)
 
1012
      {
 
1013
        assemblyName = "AssemblyName";
 
1014
#if !NETFX_CORE
 
1015
        typeName = ":::" + serializedType.Name.ToUpper(CultureInfo.InvariantCulture) + ":::";
 
1016
#else
 
1017
        typeName = ":::" + serializedType.Name.ToUpper() + ":::";
 
1018
#endif
 
1019
      }
 
1020
    }
 
1021
#endif
 
1022
 
 
1023
    [Test]
 
1024
    public void TypeNameIntList()
 
1025
    {
 
1026
      TypeNameList<int> l = new TypeNameList<int>();
 
1027
      l.Add(1);
 
1028
      l.Add(2);
 
1029
      l.Add(3);
 
1030
 
 
1031
      string json = JsonConvert.SerializeObject(l, Formatting.Indented);
 
1032
      Assert.AreEqual(@"[
 
1033
  1,
 
1034
  2,
 
1035
  3
 
1036
]", json);
 
1037
    }
 
1038
 
 
1039
    [Test]
 
1040
    public void TypeNameComponentList()
 
1041
    {
 
1042
      var c1 = new TestComponentSimple();
 
1043
 
 
1044
      TypeNameList<object> l = new TypeNameList<object>();
 
1045
      l.Add(c1);
 
1046
      l.Add(new Employee
 
1047
        {
 
1048
          BirthDate = new DateTime(2000, 12, 12, 12, 12, 12, DateTimeKind.Utc),
 
1049
          Department = "Department!"
 
1050
        });
 
1051
      l.Add("String!");
 
1052
      l.Add(long.MaxValue);
 
1053
 
 
1054
      string json = JsonConvert.SerializeObject(l, Formatting.Indented);
 
1055
      Assert.AreEqual(@"[
 
1056
  {
 
1057
    ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1058
    ""MyProperty"": 0
 
1059
  },
 
1060
  {
 
1061
    ""$type"": ""Newtonsoft.Json.Tests.TestObjects.Employee, Newtonsoft.Json.Tests"",
 
1062
    ""FirstName"": null,
 
1063
    ""LastName"": null,
 
1064
    ""BirthDate"": ""2000-12-12T12:12:12Z"",
 
1065
    ""Department"": ""Department!"",
 
1066
    ""JobTitle"": null
 
1067
  },
 
1068
  ""String!"",
 
1069
  9223372036854775807
 
1070
]", json);
 
1071
 
 
1072
      TypeNameList<object> l2 = JsonConvert.DeserializeObject<TypeNameList<object>>(json);
 
1073
      Assert.AreEqual(4, l2.Count);
 
1074
 
 
1075
      CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), l2[0]);
 
1076
      CustomAssert.IsInstanceOfType(typeof (Employee), l2[1]);
 
1077
      CustomAssert.IsInstanceOfType(typeof (string), l2[2]);
 
1078
      CustomAssert.IsInstanceOfType(typeof (long), l2[3]);
 
1079
    }
 
1080
 
 
1081
    [Test]
 
1082
    public void TypeNameDictionary()
 
1083
    {
 
1084
      TypeNameDictionary<object> l = new TypeNameDictionary<object>();
 
1085
      l.Add("First", new TestComponentSimple {MyProperty = 1});
 
1086
      l.Add("Second", "String!");
 
1087
      l.Add("Third", long.MaxValue);
 
1088
 
 
1089
      string json = JsonConvert.SerializeObject(l, Formatting.Indented);
 
1090
      Assert.AreEqual(@"{
 
1091
  ""First"": {
 
1092
    ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1093
    ""MyProperty"": 1
 
1094
  },
 
1095
  ""Second"": ""String!"",
 
1096
  ""Third"": 9223372036854775807
 
1097
}", json);
 
1098
 
 
1099
      TypeNameDictionary<object> l2 = JsonConvert.DeserializeObject<TypeNameDictionary<object>>(json);
 
1100
      Assert.AreEqual(3, l2.Count);
 
1101
 
 
1102
      CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), l2["First"]);
 
1103
      Assert.AreEqual(1, ((TestComponentSimple) l2["First"]).MyProperty);
 
1104
      CustomAssert.IsInstanceOfType(typeof (string), l2["Second"]);
 
1105
      CustomAssert.IsInstanceOfType(typeof (long), l2["Third"]);
 
1106
    }
 
1107
 
 
1108
    [Test]
 
1109
    public void TypeNameObjectItems()
 
1110
    {
 
1111
      TypeNameObject o1 = new TypeNameObject();
 
1112
 
 
1113
      o1.Object1 = new TestComponentSimple {MyProperty = 1};
 
1114
      o1.Object2 = 123;
 
1115
      o1.ObjectNotHandled = new TestComponentSimple {MyProperty = int.MaxValue};
 
1116
      o1.String = "String!";
 
1117
      o1.Integer = int.MaxValue;
 
1118
 
 
1119
      string json = JsonConvert.SerializeObject(o1, Formatting.Indented);
 
1120
      string expected = @"{
 
1121
  ""Object1"": {
 
1122
    ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1123
    ""MyProperty"": 1
 
1124
  },
 
1125
  ""Object2"": 123,
 
1126
  ""ObjectNotHandled"": {
 
1127
    ""MyProperty"": 2147483647
 
1128
  },
 
1129
  ""String"": ""String!"",
 
1130
  ""Integer"": 2147483647
 
1131
}";
 
1132
      Assert.AreEqual(expected, json);
 
1133
 
 
1134
      TypeNameObject o2 = JsonConvert.DeserializeObject<TypeNameObject>(json);
 
1135
      Assert.IsNotNull(o2);
 
1136
 
 
1137
      CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), o2.Object1);
 
1138
      Assert.AreEqual(1, ((TestComponentSimple) o2.Object1).MyProperty);
 
1139
      CustomAssert.IsInstanceOfType(typeof (long), o2.Object2);
 
1140
      CustomAssert.IsInstanceOfType(typeof (JObject), o2.ObjectNotHandled);
 
1141
      Assert.AreEqual(@"{
 
1142
  ""MyProperty"": 2147483647
 
1143
}", o2.ObjectNotHandled.ToString());
 
1144
    }
 
1145
 
 
1146
    [Test]
 
1147
    public void PropertyItemTypeNameHandling()
 
1148
    {
 
1149
      PropertyItemTypeNameHandling c1 = new PropertyItemTypeNameHandling();
 
1150
      c1.Data = new List<object>
 
1151
        {
 
1152
          1,
 
1153
          "two",
 
1154
          new TestComponentSimple {MyProperty = 1}
 
1155
        };
 
1156
 
 
1157
      string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
 
1158
      Assert.AreEqual(@"{
 
1159
  ""Data"": [
 
1160
    1,
 
1161
    ""two"",
 
1162
    {
 
1163
      ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1164
      ""MyProperty"": 1
 
1165
    }
 
1166
  ]
 
1167
}", json);
 
1168
 
 
1169
      PropertyItemTypeNameHandling c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandling>(json);
 
1170
      Assert.AreEqual(3, c2.Data.Count);
 
1171
 
 
1172
      CustomAssert.IsInstanceOfType(typeof (long), c2.Data[0]);
 
1173
      CustomAssert.IsInstanceOfType(typeof (string), c2.Data[1]);
 
1174
      CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), c2.Data[2]);
 
1175
      TestComponentSimple c = (TestComponentSimple) c2.Data[2];
 
1176
      Assert.AreEqual(1, c.MyProperty);
 
1177
    }
 
1178
 
 
1179
    [Test]
 
1180
    public void PropertyItemTypeNameHandlingNestedCollections()
 
1181
    {
 
1182
      PropertyItemTypeNameHandling c1 = new PropertyItemTypeNameHandling
 
1183
        {
 
1184
          Data = new List<object>
 
1185
            {
 
1186
              new TestComponentSimple {MyProperty = 1},
 
1187
              new List<object>
 
1188
                {
 
1189
                  new List<object>
 
1190
                    {
 
1191
                      new List<object>()
 
1192
                    }
 
1193
                }
 
1194
            }
 
1195
        };
 
1196
 
 
1197
      string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
 
1198
      Assert.AreEqual(@"{
 
1199
  ""Data"": [
 
1200
    {
 
1201
      ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1202
      ""MyProperty"": 1
 
1203
    },
 
1204
    {
 
1205
      ""$type"": ""System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib"",
 
1206
      ""$values"": [
 
1207
        [
 
1208
          []
 
1209
        ]
 
1210
      ]
 
1211
    }
 
1212
  ]
 
1213
}", json);
 
1214
 
 
1215
      PropertyItemTypeNameHandling c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandling>(json);
 
1216
      Assert.AreEqual(2, c2.Data.Count);
 
1217
 
 
1218
      CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), c2.Data[0]);
 
1219
      CustomAssert.IsInstanceOfType(typeof (List<object>), c2.Data[1]);
 
1220
      List<object> c = (List<object>) c2.Data[1];
 
1221
      CustomAssert.IsInstanceOfType(typeof (JArray), c[0]);
 
1222
 
 
1223
      json = @"{
 
1224
  ""Data"": [
 
1225
    {
 
1226
      ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1227
      ""MyProperty"": 1
 
1228
    },
 
1229
    {
 
1230
      ""$type"": ""System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib"",
 
1231
      ""$values"": [
 
1232
        {
 
1233
          ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1234
          ""MyProperty"": 1
 
1235
        }
 
1236
      ]
 
1237
    }
 
1238
  ]
 
1239
}";
 
1240
 
 
1241
      c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandling>(json);
 
1242
      Assert.AreEqual(2, c2.Data.Count);
 
1243
 
 
1244
      CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), c2.Data[0]);
 
1245
      CustomAssert.IsInstanceOfType(typeof (List<object>), c2.Data[1]);
 
1246
      c = (List<object>) c2.Data[1];
 
1247
      CustomAssert.IsInstanceOfType(typeof (JObject), c[0]);
 
1248
      JObject o = (JObject) c[0];
 
1249
      Assert.AreEqual(1, (int) o["MyProperty"]);
 
1250
    }
 
1251
 
 
1252
    [Test]
 
1253
    public void PropertyItemTypeNameHandlingNestedDictionaries()
 
1254
    {
 
1255
      PropertyItemTypeNameHandlingDictionary c1 = new PropertyItemTypeNameHandlingDictionary()
 
1256
        {
 
1257
          Data = new Dictionary<string, object>
 
1258
            {
 
1259
              {
 
1260
                "one", new TestComponentSimple {MyProperty = 1}
 
1261
              },
 
1262
              {
 
1263
                "two", new Dictionary<string, object>
 
1264
                  {
 
1265
                    {
 
1266
                      "one", new Dictionary<string, object>
 
1267
                      {
 
1268
                        {"one", 1}
 
1269
                      }
 
1270
                    }
 
1271
                  }
 
1272
              }
 
1273
            }
 
1274
        };
 
1275
 
 
1276
      string json = JsonConvert.SerializeObject(c1, Formatting.Indented);
 
1277
      Assert.AreEqual(@"{
 
1278
  ""Data"": {
 
1279
    ""one"": {
 
1280
      ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1281
      ""MyProperty"": 1
 
1282
    },
 
1283
    ""two"": {
 
1284
      ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",
 
1285
      ""one"": {
 
1286
        ""one"": 1
 
1287
      }
 
1288
    }
 
1289
  }
 
1290
}", json);
 
1291
 
 
1292
      PropertyItemTypeNameHandlingDictionary c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingDictionary>(json);
 
1293
      Assert.AreEqual(2, c2.Data.Count);
 
1294
 
 
1295
      CustomAssert.IsInstanceOfType(typeof (TestComponentSimple), c2.Data["one"]);
 
1296
      CustomAssert.IsInstanceOfType(typeof(Dictionary<string, object>), c2.Data["two"]);
 
1297
      Dictionary<string, object> c = (Dictionary<string, object>)c2.Data["two"];
 
1298
      CustomAssert.IsInstanceOfType(typeof (JObject), c["one"]);
 
1299
 
 
1300
      json = @"{
 
1301
  ""Data"": {
 
1302
    ""one"": {
 
1303
      ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1304
      ""MyProperty"": 1
 
1305
    },
 
1306
    ""two"": {
 
1307
      ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Object, mscorlib]], mscorlib"",
 
1308
      ""one"": {
 
1309
        ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1310
        ""MyProperty"": 1
 
1311
      }
 
1312
    }
 
1313
  }
 
1314
}";
 
1315
 
 
1316
      c2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingDictionary>(json);
 
1317
      Assert.AreEqual(2, c2.Data.Count);
 
1318
 
 
1319
      CustomAssert.IsInstanceOfType(typeof(TestComponentSimple), c2.Data["one"]);
 
1320
      CustomAssert.IsInstanceOfType(typeof(Dictionary<string, object>), c2.Data["two"]);
 
1321
      c = (Dictionary<string, object>)c2.Data["two"];
 
1322
      CustomAssert.IsInstanceOfType(typeof(JObject), c["one"]);
 
1323
 
 
1324
      JObject o = (JObject) c["one"];
 
1325
      Assert.AreEqual(1, (int) o["MyProperty"]);
 
1326
    }
 
1327
 
 
1328
    [Test]
 
1329
    public void PropertyItemTypeNameHandlingObject()
 
1330
    {
 
1331
      PropertyItemTypeNameHandlingObject o1 = new PropertyItemTypeNameHandlingObject
 
1332
        {
 
1333
          Data = new TypeNameHandlingTestObject
 
1334
            {
 
1335
              Prop1 = new List<object>
 
1336
                {
 
1337
                  new TestComponentSimple
 
1338
                    {
 
1339
                      MyProperty = 1
 
1340
                    }
 
1341
                },
 
1342
              Prop2 = new TestComponentSimple
 
1343
                {
 
1344
                  MyProperty = 1
 
1345
                },
 
1346
              Prop3 = 3,
 
1347
              Prop4 = new JObject()
 
1348
            }
 
1349
        };
 
1350
 
 
1351
      string json = JsonConvert.SerializeObject(o1, Formatting.Indented);
 
1352
      Assert.AreEqual(@"{
 
1353
  ""Data"": {
 
1354
    ""Prop1"": {
 
1355
      ""$type"": ""System.Collections.Generic.List`1[[System.Object, mscorlib]], mscorlib"",
 
1356
      ""$values"": [
 
1357
        {
 
1358
          ""MyProperty"": 1
 
1359
        }
 
1360
      ]
 
1361
    },
 
1362
    ""Prop2"": {
 
1363
      ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1364
      ""MyProperty"": 1
 
1365
    },
 
1366
    ""Prop3"": 3,
 
1367
    ""Prop4"": {}
 
1368
  }
 
1369
}", json);
 
1370
 
 
1371
      PropertyItemTypeNameHandlingObject o2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingObject>(json);
 
1372
      Assert.IsNotNull(o2);
 
1373
      Assert.IsNotNull(o2.Data);
 
1374
 
 
1375
      CustomAssert.IsInstanceOfType(typeof(List<object>), o2.Data.Prop1);
 
1376
      CustomAssert.IsInstanceOfType(typeof(TestComponentSimple), o2.Data.Prop2);
 
1377
      CustomAssert.IsInstanceOfType(typeof(long), o2.Data.Prop3);
 
1378
      CustomAssert.IsInstanceOfType(typeof(JObject), o2.Data.Prop4);
 
1379
 
 
1380
      List<object> o = (List<object>)o2.Data.Prop1;
 
1381
      JObject j = (JObject)o[0];
 
1382
      Assert.AreEqual(1, (int)j["MyProperty"]);
 
1383
    }
 
1384
 
 
1385
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
 
1386
    [Test]
 
1387
    public void PropertyItemTypeNameHandlingDynamic()
 
1388
    {
 
1389
      PropertyItemTypeNameHandlingDynamic d1 = new PropertyItemTypeNameHandlingDynamic();
 
1390
 
 
1391
      dynamic data = new DynamicDictionary();
 
1392
      data.one = new TestComponentSimple
 
1393
        {
 
1394
          MyProperty = 1
 
1395
        };
 
1396
 
 
1397
      dynamic data2 = new DynamicDictionary();
 
1398
      data2.one = new TestComponentSimple
 
1399
        {
 
1400
          MyProperty = 2
 
1401
        };
 
1402
 
 
1403
      data.two = data2;
 
1404
 
 
1405
      d1.Data = (DynamicDictionary)data;
 
1406
 
 
1407
      string json = JsonConvert.SerializeObject(d1, Formatting.Indented);
 
1408
      Assert.AreEqual(@"{
 
1409
  ""Data"": {
 
1410
    ""one"": {
 
1411
      ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1412
      ""MyProperty"": 1
 
1413
    },
 
1414
    ""two"": {
 
1415
      ""$type"": ""Newtonsoft.Json.Tests.Linq.DynamicDictionary, Newtonsoft.Json.Tests"",
 
1416
      ""one"": {
 
1417
        ""MyProperty"": 2
 
1418
      }
 
1419
    }
 
1420
  }
 
1421
}", json);
 
1422
 
 
1423
      PropertyItemTypeNameHandlingDynamic d2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingDynamic>(json);
 
1424
      Assert.IsNotNull(d2);
 
1425
      Assert.IsNotNull(d2.Data);
 
1426
 
 
1427
      dynamic data3 = d2.Data;
 
1428
      TestComponentSimple c = (TestComponentSimple)data3.one;
 
1429
      Assert.AreEqual(1, c.MyProperty);
 
1430
 
 
1431
      dynamic data4 = data3.two;
 
1432
      JObject o = (JObject)data4.one;
 
1433
      Assert.AreEqual(2, (int)o["MyProperty"]);
 
1434
 
 
1435
      json = @"{
 
1436
  ""Data"": {
 
1437
    ""one"": {
 
1438
      ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1439
      ""MyProperty"": 1
 
1440
    },
 
1441
    ""two"": {
 
1442
      ""$type"": ""Newtonsoft.Json.Tests.Linq.DynamicDictionary, Newtonsoft.Json.Tests"",
 
1443
      ""one"": {
 
1444
        ""$type"": ""Newtonsoft.Json.Tests.Serialization.TestComponentSimple, Newtonsoft.Json.Tests"",
 
1445
        ""MyProperty"": 2
 
1446
      }
 
1447
    }
 
1448
  }
 
1449
}";
 
1450
 
 
1451
      d2 = JsonConvert.DeserializeObject<PropertyItemTypeNameHandlingDynamic>(json);
 
1452
      data3 = d2.Data;
 
1453
      data4 = data3.two;
 
1454
      o = (JObject)data4.one;
 
1455
      Assert.AreEqual(2, (int)o["MyProperty"]);
 
1456
    }
 
1457
#endif
 
1458
  }
 
1459
 
 
1460
  public class Message
 
1461
  {
 
1462
    public string Address { get; set; }
 
1463
 
 
1464
    [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
 
1465
    public object Body { get; set; }
 
1466
  }
 
1467
 
 
1468
  public class SearchDetails
 
1469
  {
 
1470
    public string Query { get; set; }
 
1471
    public string Language { get; set; }
 
1472
  }
 
1473
 
 
1474
  public class Customer
 
1475
  {
 
1476
    public string Name { get; set; }
 
1477
  }
 
1478
 
 
1479
  public class Purchase
 
1480
  {
 
1481
    public string ProductName { get; set; }
 
1482
    public decimal Price { get; set; }
 
1483
    public int Quantity { get; set; }
 
1484
  }
 
1485
 
 
1486
#if !(WINDOWS_PHONE || SILVERLIGHT || NETFX_CORE)
 
1487
  public class SerializableWrapper
 
1488
  {
 
1489
    public object Content { get; set; }
 
1490
 
 
1491
    public override bool Equals(object obj)
 
1492
    {
 
1493
      SerializableWrapper w = obj as SerializableWrapper;
 
1494
 
 
1495
      if (w == null)
 
1496
        return false;
 
1497
 
 
1498
      return Equals(w.Content, Content);
 
1499
    }
 
1500
 
 
1501
    public override int GetHashCode()
 
1502
    {
 
1503
      if (Content == null)
 
1504
        return 0;
 
1505
 
 
1506
      return Content.GetHashCode();
 
1507
    }
 
1508
  }
 
1509
 
 
1510
  public interface IExample
 
1511
    : ISerializable
 
1512
  {
 
1513
    String Name
 
1514
    {
 
1515
      get;
 
1516
    }
 
1517
  }
 
1518
 
 
1519
  [Serializable]
 
1520
  public class Example
 
1521
      : IExample
 
1522
  {
 
1523
    public Example(String name)
 
1524
    {
 
1525
      this.Name = name;
 
1526
    }
 
1527
 
 
1528
    protected Example(SerializationInfo info, StreamingContext context)
 
1529
    {
 
1530
      this.Name = info.GetString("name");
 
1531
    }
 
1532
 
 
1533
    public void GetObjectData(SerializationInfo info, StreamingContext context)
 
1534
    {
 
1535
      info.AddValue("name", this.Name);
 
1536
    }
 
1537
 
 
1538
    public String Name { get; set; }
 
1539
 
 
1540
    public override bool Equals(object obj)
 
1541
    {
 
1542
      if (obj == null) return false;
 
1543
      if (ReferenceEquals(this, obj)) return true;
 
1544
      if (obj is IExample)
 
1545
      {
 
1546
        return this.Name.Equals(((IExample)obj).Name);
 
1547
      }
 
1548
      else
 
1549
      {
 
1550
        return false;
 
1551
      }
 
1552
    }
 
1553
 
 
1554
    public override int GetHashCode()
 
1555
    {
 
1556
      if (Name == null)
 
1557
        return 0;
 
1558
 
 
1559
      return Name.GetHashCode();
 
1560
    }
 
1561
  }
 
1562
#endif
 
1563
 
 
1564
  public class PropertyItemTypeNameHandlingObject
 
1565
  {
 
1566
    [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
 
1567
    public TypeNameHandlingTestObject Data { get; set; }
 
1568
  }
 
1569
 
 
1570
#if !(NET35 || NET20 || WINDOWS_PHONE || PORTABLE)
 
1571
  public class PropertyItemTypeNameHandlingDynamic
 
1572
  {
 
1573
    [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
 
1574
    public DynamicDictionary Data { get; set; }
 
1575
  }
 
1576
#endif
 
1577
 
 
1578
  public class TypeNameHandlingTestObject
 
1579
  {
 
1580
    public object Prop1 { get; set; }
 
1581
    public object Prop2 { get; set; }
 
1582
    public object Prop3 { get; set; }
 
1583
    public object Prop4 { get; set; }
 
1584
  }
 
1585
 
 
1586
  public class PropertyItemTypeNameHandlingDictionary
 
1587
  {
 
1588
    [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
 
1589
    public IDictionary<string, object> Data { get; set; }
 
1590
  }
 
1591
 
 
1592
  public class PropertyItemTypeNameHandling
 
1593
  {
 
1594
    [JsonProperty(ItemTypeNameHandling = TypeNameHandling.All)]
 
1595
    public IList<object> Data { get; set; }
 
1596
  }
 
1597
 
 
1598
  [JsonArray(ItemTypeNameHandling = TypeNameHandling.All)]
 
1599
  public class TypeNameList<T> : List<T>
 
1600
  {
 
1601
  }
 
1602
 
 
1603
  [JsonDictionary(ItemTypeNameHandling = TypeNameHandling.All)]
 
1604
  public class TypeNameDictionary<T> : Dictionary<string, T>
 
1605
  {
 
1606
  }
 
1607
 
 
1608
  [JsonObject(ItemTypeNameHandling = TypeNameHandling.All)]
 
1609
  public class TypeNameObject
 
1610
  {
 
1611
    public object Object1 { get; set; }
 
1612
    public object Object2 { get; set; }
 
1613
    [JsonProperty(TypeNameHandling = TypeNameHandling.None)]
 
1614
    public object ObjectNotHandled { get; set; }
 
1615
    public string String { get; set; }
 
1616
    public int Integer { get; set; }
 
1617
  }
 
1618
}
 
1619
#endif
 
 
b'\\ No newline at end of file'