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

« back to all changes in this revision

Viewing changes to external/Newtonsoft.Json/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.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
using System;
 
27
using System.Collections.Generic;
 
28
using System.Globalization;
 
29
#if !NETFX_CORE
 
30
using NUnit.Framework;
 
31
#else
 
32
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
 
33
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
 
34
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
 
35
#endif
 
36
using Newtonsoft.Json.Converters;
 
37
using Newtonsoft.Json.Linq;
 
38
using Newtonsoft.Json.Tests.Serialization;
 
39
using Newtonsoft.Json.Tests.TestObjects;
 
40
#if NET20
 
41
using Newtonsoft.Json.Utilities.LinqBridge;
 
42
#else
 
43
using System.Linq;
 
44
#endif
 
45
using System.IO;
 
46
 
 
47
namespace Newtonsoft.Json.Tests.Linq
 
48
{
 
49
  [TestFixture]
 
50
  public class LinqToJsonTest : TestFixtureBase
 
51
  {
 
52
    [Test]
 
53
    public void DoubleValue()
 
54
    {
 
55
      JArray j = JArray.Parse("[-1E+4,100.0e-2]");
 
56
 
 
57
      double value = (double)j[0];
 
58
      Assert.AreEqual(-10000d, value);
 
59
 
 
60
      value = (double)j[1];
 
61
      Assert.AreEqual(1d, value);
 
62
    }
 
63
 
 
64
    [Test]
 
65
    public void Manual()
 
66
    {
 
67
      JArray array = new JArray();
 
68
      JValue text = new JValue("Manual text");
 
69
      JValue date = new JValue(new DateTime(2000, 5, 23));
 
70
 
 
71
      array.Add(text);
 
72
      array.Add(date);
 
73
 
 
74
      string json = array.ToString();
 
75
      // [
 
76
      //   "Manual text",
 
77
      //   "\/Date(958996800000+1200)\/"
 
78
      // ]
 
79
    }
 
80
 
 
81
    [Test]
 
82
    public void LinqToJsonDeserialize()
 
83
    {
 
84
      JObject o = new JObject(
 
85
        new JProperty("Name", "John Smith"),
 
86
        new JProperty("BirthDate", new DateTime(1983, 3, 20))
 
87
        );
 
88
 
 
89
      JsonSerializer serializer = new JsonSerializer();
 
90
      Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
 
91
 
 
92
      // John Smith
 
93
      Console.WriteLine(p.Name);
 
94
    }
 
95
 
 
96
    [Test]
 
97
    public void ObjectParse()
 
98
    {
 
99
      string json = @"{
 
100
        CPU: 'Intel',
 
101
        Drives: [
 
102
          'DVD read/writer',
 
103
          ""500 gigabyte hard drive""
 
104
        ]
 
105
      }";
 
106
 
 
107
      JObject o = JObject.Parse(json);
 
108
      IList<JProperty> properties = o.Properties().ToList();
 
109
 
 
110
      Assert.AreEqual("CPU", properties[0].Name);
 
111
      Assert.AreEqual("Intel", (string)properties[0].Value);
 
112
      Assert.AreEqual("Drives", properties[1].Name);
 
113
 
 
114
      JArray list = (JArray)properties[1].Value;
 
115
      Assert.AreEqual(2, list.Children().Count());
 
116
      Assert.AreEqual("DVD read/writer", (string)list.Children().ElementAt(0));
 
117
      Assert.AreEqual("500 gigabyte hard drive", (string)list.Children().ElementAt(1));
 
118
 
 
119
      List<object> parameterValues =
 
120
        (from p in o.Properties()
 
121
         where p.Value is JValue
 
122
         select ((JValue)p.Value).Value).ToList();
 
123
 
 
124
      Assert.AreEqual(1, parameterValues.Count);
 
125
      Assert.AreEqual("Intel", parameterValues[0]);
 
126
    }
 
127
 
 
128
    [Test]
 
129
    public void CreateLongArray()
 
130
    {
 
131
      string json = @"[0,1,2,3,4,5,6,7,8,9]";
 
132
 
 
133
      JArray a = JArray.Parse(json);
 
134
      List<int> list = a.Values<int>().ToList();
 
135
 
 
136
      List<int> expected = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
137
 
 
138
      CollectionAssert.AreEqual(expected, list);
 
139
    }
 
140
 
 
141
    [Test]
 
142
    public void GoogleSearchAPI()
 
143
    {
 
144
      #region GoogleJson
 
145
      string json = @"{
 
146
    results:
 
147
        [
 
148
            {
 
149
                GsearchResultClass:""GwebSearch"",
 
150
                unescapedUrl : ""http://www.google.com/"",
 
151
                url : ""http://www.google.com/"",
 
152
                visibleUrl : ""www.google.com"",
 
153
                cacheUrl : 
 
154
""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
 
155
                title : ""Google"",
 
156
                titleNoFormatting : ""Google"",
 
157
                content : ""Enables users to search the Web, Usenet, and 
 
158
images. Features include PageRank,   caching and translation of 
 
159
results, and an option to find similar pages.""
 
160
            },
 
161
            {
 
162
                GsearchResultClass:""GwebSearch"",
 
163
                unescapedUrl : ""http://news.google.com/"",
 
164
                url : ""http://news.google.com/"",
 
165
                visibleUrl : ""news.google.com"",
 
166
                cacheUrl : 
 
167
""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
 
168
                title : ""Google News"",
 
169
                titleNoFormatting : ""Google News"",
 
170
                content : ""Aggregated headlines and a search engine of many of the world's news sources.""
 
171
            },
 
172
            
 
173
            {
 
174
                GsearchResultClass:""GwebSearch"",
 
175
                unescapedUrl : ""http://groups.google.com/"",
 
176
                url : ""http://groups.google.com/"",
 
177
                visibleUrl : ""groups.google.com"",
 
178
                cacheUrl : 
 
179
""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
 
180
                title : ""Google Groups"",
 
181
                titleNoFormatting : ""Google Groups"",
 
182
                content : ""Enables users to search and browse the Usenet 
 
183
archives which consist of over 700   million messages, and post new 
 
184
comments.""
 
185
            },
 
186
            
 
187
            {
 
188
                GsearchResultClass:""GwebSearch"",
 
189
                unescapedUrl : ""http://maps.google.com/"",
 
190
                url : ""http://maps.google.com/"",
 
191
                visibleUrl : ""maps.google.com"",
 
192
                cacheUrl : 
 
193
""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
 
194
                title : ""Google Maps"",
 
195
                titleNoFormatting : ""Google Maps"",
 
196
                content : ""Provides directions, interactive maps, and 
 
197
satellite/aerial imagery of the United   States. Can also search by 
 
198
keyword such as type of business.""
 
199
            }
 
200
        ],
 
201
        
 
202
    adResults:
 
203
        [
 
204
            {
 
205
                GsearchResultClass:""GwebSearch.ad"",
 
206
                title : ""Gartner Symposium/ITxpo"",
 
207
                content1 : ""Meet brilliant Gartner IT analysts"",
 
208
                content2 : ""20-23 May 2007- Barcelona, Spain"",
 
209
                url : 
 
210
""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="", 
 
211
 
 
212
                impressionUrl : 
 
213
""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"", 
 
214
 
 
215
                unescapedUrl : 
 
216
""http://www.google.com/url?sa=L&ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB&num=1&q=http://www.gartner.com/it/sym/2007/spr8/spr8.jsp%3Fsrc%3D_spain_07_%26WT.srch%3D1&usg=__CxRH06E4Xvm9Muq13S4MgMtnziY="", 
 
217
 
 
218
                visibleUrl : ""www.gartner.com""
 
219
            }
 
220
        ]
 
221
}
 
222
";
 
223
      #endregion
 
224
 
 
225
      JObject o = JObject.Parse(json);
 
226
 
 
227
      List<JObject> resultObjects = o["results"].Children<JObject>().ToList();
 
228
 
 
229
      Assert.AreEqual(32, resultObjects.Properties().Count());
 
230
 
 
231
      Assert.AreEqual(32, resultObjects.Cast<JToken>().Values().Count());
 
232
 
 
233
      Assert.AreEqual(4, resultObjects.Cast<JToken>().Values("GsearchResultClass").Count());
 
234
 
 
235
      Assert.AreEqual(5, o.PropertyValues().Cast<JArray>().Children().Count());
 
236
 
 
237
      List<string> resultUrls = o["results"].Children().Values<string>("url").ToList();
 
238
 
 
239
      List<string> expectedUrls = new List<string>() { "http://www.google.com/", "http://news.google.com/", "http://groups.google.com/", "http://maps.google.com/" };
 
240
 
 
241
      CollectionAssert.AreEqual(expectedUrls, resultUrls);
 
242
 
 
243
      List<JToken> descendants = o.Descendants().ToList();
 
244
      Assert.AreEqual(89, descendants.Count);
 
245
    }
 
246
 
 
247
    [Test]
 
248
    public void JTokenToString()
 
249
    {
 
250
      string json = @"{
 
251
  CPU: 'Intel',
 
252
  Drives: [
 
253
    'DVD read/writer',
 
254
    ""500 gigabyte hard drive""
 
255
  ]
 
256
}";
 
257
 
 
258
      JObject o = JObject.Parse(json);
 
259
 
 
260
      Assert.AreEqual(@"{
 
261
  ""CPU"": ""Intel"",
 
262
  ""Drives"": [
 
263
    ""DVD read/writer"",
 
264
    ""500 gigabyte hard drive""
 
265
  ]
 
266
}", o.ToString());
 
267
 
 
268
      JArray list = o.Value<JArray>("Drives");
 
269
 
 
270
      Assert.AreEqual(@"[
 
271
  ""DVD read/writer"",
 
272
  ""500 gigabyte hard drive""
 
273
]", list.ToString());
 
274
 
 
275
      JProperty cpuProperty = o.Property("CPU");
 
276
      Assert.AreEqual(@"""CPU"": ""Intel""", cpuProperty.ToString());
 
277
 
 
278
      JProperty drivesProperty = o.Property("Drives");
 
279
      Assert.AreEqual(@"""Drives"": [
 
280
  ""DVD read/writer"",
 
281
  ""500 gigabyte hard drive""
 
282
]", drivesProperty.ToString());
 
283
    }
 
284
 
 
285
    [Test]
 
286
    public void JTokenToStringTypes()
 
287
    {
 
288
      string json = @"{""Color"":2,""Establised"":new Date(1264118400000),""Width"":1.1,""Employees"":999,""RoomsPerFloor"":[1,2,3,4,5,6,7,8,9],""Open"":false,""Symbol"":""@"",""Mottos"":[""Hello World"",""Ć¶Ć¤Ć¼Ć–Ć„Ćœ\\'{new Date(12345);}[222]_Āµ@Ā²Ā³~"",null,"" ""],""Cost"":100980.1,""Escape"":""\r\n\t\f\b?{\\r\\n\""'"",""product"":[{""Name"":""Rocket"",""ExpiryDate"":new Date(949532490000),""Price"":0},{""Name"":""Alien"",""ExpiryDate"":new Date(-62135596800000),""Price"":0}]}";
 
289
 
 
290
      JObject o = JObject.Parse(json);
 
291
 
 
292
      Assert.AreEqual(@"""Establised"": new Date(
 
293
  1264118400000
 
294
)", o.Property("Establised").ToString());
 
295
      Assert.AreEqual(@"new Date(
 
296
  1264118400000
 
297
)", o.Property("Establised").Value.ToString());
 
298
      Assert.AreEqual(@"""Width"": 1.1", o.Property("Width").ToString());
 
299
      Assert.AreEqual(@"1.1", ((JValue)o.Property("Width").Value).ToString(CultureInfo.InvariantCulture));
 
300
      Assert.AreEqual(@"""Open"": false", o.Property("Open").ToString());
 
301
      Assert.AreEqual(@"False", o.Property("Open").Value.ToString());
 
302
 
 
303
      json = @"[null,undefined]";
 
304
 
 
305
      JArray a = JArray.Parse(json);
 
306
      Assert.AreEqual(@"[
 
307
  null,
 
308
  undefined
 
309
]", a.ToString());
 
310
      Assert.AreEqual(@"", a.Children().ElementAt(0).ToString());
 
311
      Assert.AreEqual(@"", a.Children().ElementAt(1).ToString());
 
312
    }
 
313
 
 
314
    [Test]
 
315
    public void CreateJTokenTree()
 
316
    {
 
317
      JObject o =
 
318
        new JObject(
 
319
          new JProperty("Test1", "Test1Value"),
 
320
          new JProperty("Test2", "Test2Value"),
 
321
          new JProperty("Test3", "Test3Value"),
 
322
          new JProperty("Test4", null)
 
323
        );
 
324
 
 
325
      Assert.AreEqual(4, o.Properties().Count());
 
326
 
 
327
      Assert.AreEqual(@"{
 
328
  ""Test1"": ""Test1Value"",
 
329
  ""Test2"": ""Test2Value"",
 
330
  ""Test3"": ""Test3Value"",
 
331
  ""Test4"": null
 
332
}", o.ToString());
 
333
 
 
334
      JArray a =
 
335
        new JArray(
 
336
          o,
 
337
          new DateTime(2000, 10, 10, 0, 0, 0, DateTimeKind.Utc),
 
338
          55,
 
339
          new JArray(
 
340
            "1",
 
341
            2,
 
342
            3.0,
 
343
            new DateTime(4, 5, 6, 7, 8, 9, DateTimeKind.Utc)
 
344
          ),
 
345
          new JConstructor(
 
346
            "ConstructorName",
 
347
            "param1",
 
348
            2,
 
349
            3.0
 
350
          )
 
351
        );
 
352
 
 
353
      Assert.AreEqual(5, a.Count());
 
354
      Assert.AreEqual(@"[
 
355
  {
 
356
    ""Test1"": ""Test1Value"",
 
357
    ""Test2"": ""Test2Value"",
 
358
    ""Test3"": ""Test3Value"",
 
359
    ""Test4"": null
 
360
  },
 
361
  ""2000-10-10T00:00:00Z"",
 
362
  55,
 
363
  [
 
364
    ""1"",
 
365
    2,
 
366
    3.0,
 
367
    ""0004-05-06T07:08:09Z""
 
368
  ],
 
369
  new ConstructorName(
 
370
    ""param1"",
 
371
    2,
 
372
    3.0
 
373
  )
 
374
]", a.ToString());
 
375
    }
 
376
 
 
377
    private class Post
 
378
    {
 
379
      public string Title { get; set; }
 
380
      public string Description { get; set; }
 
381
      public string Link { get; set; }
 
382
      public IList<string> Categories { get; set; }
 
383
    }
 
384
 
 
385
    private List<Post> GetPosts()
 
386
    {
 
387
      return new List<Post>()
 
388
      {
 
389
        new Post()
 
390
        {
 
391
          Title = "LINQ to JSON beta",
 
392
          Description = "Annoucing LINQ to JSON",
 
393
          Link = "http://james.newtonking.com/projects/json-net.aspx",
 
394
          Categories = new List<string>() { "Json.NET", "LINQ" }
 
395
        },
 
396
        new Post()
 
397
        {
 
398
          Title = "Json.NET 1.3 + New license + Now on CodePlex",
 
399
          Description = "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
 
400
          Link = "http://james.newtonking.com/projects/json-net.aspx",
 
401
          Categories = new List<string>() { "Json.NET", "CodePlex" }
 
402
        }
 
403
      };
 
404
    }
 
405
 
 
406
    [Test]
 
407
    public void CreateJTokenTreeNested()
 
408
    {
 
409
      List<Post> posts = GetPosts();
 
410
 
 
411
      JObject rss =
 
412
        new JObject(
 
413
          new JProperty("channel",
 
414
            new JObject(
 
415
              new JProperty("title", "James Newton-King"),
 
416
              new JProperty("link", "http://james.newtonking.com"),
 
417
              new JProperty("description", "James Newton-King's blog."),
 
418
              new JProperty("item",
 
419
                new JArray(
 
420
                  from p in posts
 
421
                  orderby p.Title
 
422
                  select new JObject(
 
423
                    new JProperty("title", p.Title),
 
424
                    new JProperty("description", p.Description),
 
425
                    new JProperty("link", p.Link),
 
426
                    new JProperty("category",
 
427
                      new JArray(
 
428
                        from c in p.Categories
 
429
                        select new JValue(c)))))))));
 
430
 
 
431
      Console.WriteLine(rss.ToString());
 
432
 
 
433
      //{
 
434
      //  "channel": {
 
435
      //    "title": "James Newton-King",
 
436
      //    "link": "http://james.newtonking.com",
 
437
      //    "description": "James Newton-King's blog.",
 
438
      //    "item": [
 
439
      //      {
 
440
      //        "title": "Json.NET 1.3 + New license + Now on CodePlex",
 
441
      //        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
 
442
      //        "link": "http://james.newtonking.com/projects/json-net.aspx",
 
443
      //        "category": [
 
444
      //          "Json.NET",
 
445
      //          "CodePlex"
 
446
      //        ]
 
447
      //      },
 
448
      //      {
 
449
      //        "title": "LINQ to JSON beta",
 
450
      //        "description": "Annoucing LINQ to JSON",
 
451
      //        "link": "http://james.newtonking.com/projects/json-net.aspx",
 
452
      //        "category": [
 
453
      //          "Json.NET",
 
454
      //          "LINQ"
 
455
      //        ]
 
456
      //      }
 
457
      //    ]
 
458
      //  }
 
459
      //}
 
460
 
 
461
      var postTitles =
 
462
        from p in rss["channel"]["item"]
 
463
        select p.Value<string>("title");
 
464
 
 
465
      foreach (var item in postTitles)
 
466
      {
 
467
        Console.WriteLine(item);
 
468
      }
 
469
 
 
470
      //LINQ to JSON beta
 
471
      //Json.NET 1.3 + New license + Now on CodePlex
 
472
 
 
473
      var categories =
 
474
        from c in rss["channel"]["item"].Children()["category"].Values<string>()
 
475
        group c by c into g
 
476
        orderby g.Count() descending
 
477
        select new { Category = g.Key, Count = g.Count() };
 
478
 
 
479
      foreach (var c in categories)
 
480
      {
 
481
        Console.WriteLine(c.Category + " - Count: " + c.Count);
 
482
      }
 
483
 
 
484
      //Json.NET - Count: 2
 
485
      //LINQ - Count: 1
 
486
      //CodePlex - Count: 1
 
487
    }
 
488
 
 
489
    [Test]
 
490
    public void BasicQuerying()
 
491
    {
 
492
      string json = @"{
 
493
                        ""channel"": {
 
494
                          ""title"": ""James Newton-King"",
 
495
                          ""link"": ""http://james.newtonking.com"",
 
496
                          ""description"": ""James Newton-King's blog."",
 
497
                          ""item"": [
 
498
                            {
 
499
                              ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
 
500
                              ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
 
501
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
 
502
                              ""category"": [
 
503
                                ""Json.NET"",
 
504
                                ""CodePlex""
 
505
                              ]
 
506
                            },
 
507
                            {
 
508
                              ""title"": ""LINQ to JSON beta"",
 
509
                              ""description"": ""Annoucing LINQ to JSON"",
 
510
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
 
511
                              ""category"": [
 
512
                                ""Json.NET"",
 
513
                                ""LINQ""
 
514
                              ]
 
515
                            }
 
516
                          ]
 
517
                        }
 
518
                      }";
 
519
 
 
520
      JObject o = JObject.Parse(json);
 
521
 
 
522
      Assert.AreEqual(null, o["purple"]);
 
523
      Assert.AreEqual(null, o.Value<string>("purple"));
 
524
 
 
525
      CustomAssert.IsInstanceOfType(typeof(JArray), o["channel"]["item"]);
 
526
 
 
527
      Assert.AreEqual(2, o["channel"]["item"].Children()["title"].Count());
 
528
      Assert.AreEqual(0, o["channel"]["item"].Children()["monkey"].Count());
 
529
 
 
530
      Assert.AreEqual("Json.NET 1.3 + New license + Now on CodePlex", (string)o["channel"]["item"][0]["title"]);
 
531
 
 
532
      CollectionAssert.AreEqual(new string[] { "Json.NET 1.3 + New license + Now on CodePlex", "LINQ to JSON beta" }, o["channel"]["item"].Children().Values<string>("title").ToArray());
 
533
    }
 
534
 
 
535
    [Test]
 
536
    public void JObjectIntIndex()
 
537
    {
 
538
      ExceptionAssert.Throws<ArgumentException>("Accessed JObject values with invalid key value: 0. Object property name expected.",
 
539
      () =>
 
540
      {
 
541
        JObject o = new JObject();
 
542
        Assert.AreEqual(null, o[0]);
 
543
      });
 
544
    }
 
545
 
 
546
    [Test]
 
547
    public void JArrayStringIndex()
 
548
    {
 
549
      ExceptionAssert.Throws<ArgumentException>(@"Accessed JArray values with invalid key value: ""purple"". Array position index expected.",
 
550
      () =>
 
551
      {
 
552
        JArray a = new JArray();
 
553
        Assert.AreEqual(null, a["purple"]);
 
554
      });
 
555
    }
 
556
 
 
557
    [Test]
 
558
    public void JConstructorStringIndex()
 
559
    {
 
560
      ExceptionAssert.Throws<ArgumentException>(@"Accessed JConstructor values with invalid key value: ""purple"". Argument position index expected.",
 
561
      () =>
 
562
      {
 
563
        JConstructor c = new JConstructor("ConstructorValue");
 
564
        Assert.AreEqual(null, c["purple"]);
 
565
      });
 
566
    }
 
567
 
 
568
#if !PocketPC && !NET20
 
569
    [Test]
 
570
    public void ToStringJsonConverter()
 
571
    {
 
572
      JObject o =
 
573
        new JObject(
 
574
          new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)),
 
575
          new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))),
 
576
          new JProperty("Test3", "Test3Value"),
 
577
          new JProperty("Test4", null)
 
578
        );
 
579
 
 
580
      JsonSerializer serializer = new JsonSerializer();
 
581
      serializer.Converters.Add(new JavaScriptDateTimeConverter());
 
582
      StringWriter sw = new StringWriter();
 
583
      JsonWriter writer = new JsonTextWriter(sw);
 
584
      writer.Formatting = Formatting.Indented;
 
585
      serializer.Serialize(writer, o);
 
586
 
 
587
      string json = sw.ToString();
 
588
 
 
589
      Assert.AreEqual(@"{
 
590
  ""Test1"": new Date(
 
591
    971586305000
 
592
  ),
 
593
  ""Test2"": new Date(
 
594
    971546045000
 
595
  ),
 
596
  ""Test3"": ""Test3Value"",
 
597
  ""Test4"": null
 
598
}", json);
 
599
    }
 
600
 
 
601
    [Test]
 
602
    public void DateTimeOffset()
 
603
    {
 
604
      List<DateTimeOffset> testDates = new List<DateTimeOffset> {
 
605
        new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
 
606
        new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
 
607
        new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
 
608
        new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
 
609
      };
 
610
 
 
611
      JsonSerializer jsonSerializer = new JsonSerializer();
 
612
 
 
613
      JTokenWriter jsonWriter;
 
614
      using (jsonWriter = new JTokenWriter())
 
615
      {
 
616
        jsonSerializer.Serialize(jsonWriter, testDates);
 
617
      }
 
618
 
 
619
      Assert.AreEqual(4, jsonWriter.Token.Children().Count());
 
620
    }
 
621
#endif
 
622
 
 
623
    [Test]
 
624
    public void FromObject()
 
625
    {
 
626
      List<Post> posts = GetPosts();
 
627
 
 
628
      JObject o = JObject.FromObject(new
 
629
      {
 
630
        channel = new
 
631
        {
 
632
          title = "James Newton-King",
 
633
          link = "http://james.newtonking.com",
 
634
          description = "James Newton-King's blog.",
 
635
          item =
 
636
              from p in posts
 
637
              orderby p.Title
 
638
              select new
 
639
              {
 
640
                title = p.Title,
 
641
                description = p.Description,
 
642
                link = p.Link,
 
643
                category = p.Categories
 
644
              }
 
645
        }
 
646
      });
 
647
 
 
648
      Console.WriteLine(o.ToString());
 
649
      CustomAssert.IsInstanceOfType(typeof(JObject), o);
 
650
      CustomAssert.IsInstanceOfType(typeof(JObject), o["channel"]);
 
651
      Assert.AreEqual("James Newton-King", (string)o["channel"]["title"]);
 
652
      Assert.AreEqual(2, o["channel"]["item"].Children().Count());
 
653
 
 
654
      JArray a = JArray.FromObject(new List<int>() { 0, 1, 2, 3, 4 });
 
655
      CustomAssert.IsInstanceOfType(typeof(JArray), a);
 
656
      Assert.AreEqual(5, a.Count());
 
657
    }
 
658
 
 
659
    [Test]
 
660
    public void FromAnonDictionary()
 
661
    {
 
662
      List<Post> posts = GetPosts();
 
663
 
 
664
      JObject o = JObject.FromObject(new
 
665
      {
 
666
        channel = new Dictionary<string, object>
 
667
        {
 
668
          { "title", "James Newton-King" },
 
669
          { "link", "http://james.newtonking.com" },
 
670
          { "description", "James Newton-King's blog." },
 
671
          { "item", 
 
672
                  (from p in posts
 
673
                  orderby p.Title
 
674
                  select new
 
675
                  {
 
676
                    title = p.Title,
 
677
                    description = p.Description,
 
678
                    link = p.Link,
 
679
                    category = p.Categories
 
680
                  })
 
681
          }
 
682
        }
 
683
      });
 
684
 
 
685
      Console.WriteLine(o.ToString());
 
686
      CustomAssert.IsInstanceOfType(typeof(JObject), o);
 
687
      CustomAssert.IsInstanceOfType(typeof(JObject), o["channel"]);
 
688
      Assert.AreEqual("James Newton-King", (string)o["channel"]["title"]);
 
689
      Assert.AreEqual(2, o["channel"]["item"].Children().Count());
 
690
 
 
691
      JArray a = JArray.FromObject(new List<int>() { 0, 1, 2, 3, 4 });
 
692
      CustomAssert.IsInstanceOfType(typeof(JArray), a);
 
693
      Assert.AreEqual(5, a.Count());
 
694
    }
 
695
 
 
696
    [Test]
 
697
    public void AsJEnumerable()
 
698
    {
 
699
      JObject o = null;
 
700
      IJEnumerable<JToken> enumerable = null;
 
701
 
 
702
      enumerable = o.AsJEnumerable();
 
703
      Assert.IsNull(enumerable);
 
704
    
 
705
      o =
 
706
        new JObject(
 
707
          new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)),
 
708
          new JProperty("Test2", "Test2Value"),
 
709
          new JProperty("Test3", null)
 
710
        );
 
711
 
 
712
      enumerable = o.AsJEnumerable();
 
713
      Assert.IsNotNull(enumerable);
 
714
      Assert.AreEqual(o, enumerable);
 
715
 
 
716
      DateTime d = enumerable["Test1"].Value<DateTime>();
 
717
 
 
718
      Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), d);
 
719
    }
 
720
 
 
721
#if !(NET20 || NET35 || SILVERLIGHT || PORTABLE)
 
722
    [Test]
 
723
    public void CovariantIJEnumerable()
 
724
    {
 
725
      IEnumerable<JObject> o = new[]
 
726
        {
 
727
          JObject.FromObject(new {First = 1, Second = 2}),
 
728
          JObject.FromObject(new {First = 1, Second = 2})
 
729
        };
 
730
 
 
731
      IJEnumerable<JToken> values = o.Properties();
 
732
      Assert.AreEqual(4, values.Count());
 
733
    }
 
734
#endif
 
735
 
 
736
    [Test]
 
737
    public void ChildrenExtension()
 
738
    {
 
739
      string json = @"[
 
740
                        {
 
741
                          ""title"": ""James Newton-King"",
 
742
                          ""link"": ""http://james.newtonking.com"",
 
743
                          ""description"": ""James Newton-King's blog."",
 
744
                          ""item"": [
 
745
                            {
 
746
                              ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
 
747
                              ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
 
748
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
 
749
                              ""category"": [
 
750
                                ""Json.NET"",
 
751
                                ""CodePlex""
 
752
                              ]
 
753
                            },
 
754
                            {
 
755
                              ""title"": ""LINQ to JSON beta"",
 
756
                              ""description"": ""Annoucing LINQ to JSON"",
 
757
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
 
758
                              ""category"": [
 
759
                                ""Json.NET"",
 
760
                                ""LINQ""
 
761
                              ]
 
762
                            }
 
763
                          ]
 
764
                        },
 
765
                        {
 
766
                          ""title"": ""James Newton-King"",
 
767
                          ""link"": ""http://james.newtonking.com"",
 
768
                          ""description"": ""James Newton-King's blog."",
 
769
                          ""item"": [
 
770
                            {
 
771
                              ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
 
772
                              ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
 
773
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
 
774
                              ""category"": [
 
775
                                ""Json.NET"",
 
776
                                ""CodePlex""
 
777
                              ]
 
778
                            },
 
779
                            {
 
780
                              ""title"": ""LINQ to JSON beta"",
 
781
                              ""description"": ""Annoucing LINQ to JSON"",
 
782
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
 
783
                              ""category"": [
 
784
                                ""Json.NET"",
 
785
                                ""LINQ""
 
786
                              ]
 
787
                            }
 
788
                          ]
 
789
                        }
 
790
                      ]";
 
791
 
 
792
      JArray o = JArray.Parse(json);
 
793
 
 
794
      Assert.AreEqual(4, o.Children()["item"].Children()["title"].Count());
 
795
      CollectionAssert.AreEqual(new string[]
 
796
        {
 
797
          "Json.NET 1.3 + New license + Now on CodePlex",
 
798
          "LINQ to JSON beta",
 
799
          "Json.NET 1.3 + New license + Now on CodePlex",
 
800
          "LINQ to JSON beta"
 
801
        },
 
802
        o.Children()["item"].Children()["title"].Values<string>().ToArray());
 
803
    }
 
804
 
 
805
    [Test]
 
806
    public void UriGuidTimeSpanTestClassEmptyTest()
 
807
    {
 
808
      UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass();
 
809
      JObject o = JObject.FromObject(c1);
 
810
 
 
811
      Assert.AreEqual(@"{
 
812
  ""Guid"": ""00000000-0000-0000-0000-000000000000"",
 
813
  ""NullableGuid"": null,
 
814
  ""TimeSpan"": ""00:00:00"",
 
815
  ""NullableTimeSpan"": null,
 
816
  ""Uri"": null
 
817
}", o.ToString());
 
818
 
 
819
      UriGuidTimeSpanTestClass c2 = o.ToObject<UriGuidTimeSpanTestClass>();
 
820
      Assert.AreEqual(c1.Guid, c2.Guid);
 
821
      Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
 
822
      Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
 
823
      Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
 
824
      Assert.AreEqual(c1.Uri, c2.Uri);
 
825
    }
 
826
 
 
827
    [Test]
 
828
    public void UriGuidTimeSpanTestClassValuesTest()
 
829
    {
 
830
      UriGuidTimeSpanTestClass c1 = new UriGuidTimeSpanTestClass
 
831
      {
 
832
        Guid = new Guid("1924129C-F7E0-40F3-9607-9939C531395A"),
 
833
        NullableGuid = new Guid("9E9F3ADF-E017-4F72-91E0-617EBE85967D"),
 
834
        TimeSpan = TimeSpan.FromDays(1),
 
835
        NullableTimeSpan = TimeSpan.FromHours(1),
 
836
        Uri = new Uri("http://testuri.com")
 
837
      };
 
838
      JObject o = JObject.FromObject(c1);
 
839
 
 
840
      Assert.AreEqual(@"{
 
841
  ""Guid"": ""1924129c-f7e0-40f3-9607-9939c531395a"",
 
842
  ""NullableGuid"": ""9e9f3adf-e017-4f72-91e0-617ebe85967d"",
 
843
  ""TimeSpan"": ""1.00:00:00"",
 
844
  ""NullableTimeSpan"": ""01:00:00"",
 
845
  ""Uri"": ""http://testuri.com/""
 
846
}", o.ToString());
 
847
 
 
848
      UriGuidTimeSpanTestClass c2 = o.ToObject<UriGuidTimeSpanTestClass>();
 
849
      Assert.AreEqual(c1.Guid, c2.Guid);
 
850
      Assert.AreEqual(c1.NullableGuid, c2.NullableGuid);
 
851
      Assert.AreEqual(c1.TimeSpan, c2.TimeSpan);
 
852
      Assert.AreEqual(c1.NullableTimeSpan, c2.NullableTimeSpan);
 
853
      Assert.AreEqual(c1.Uri, c2.Uri);
 
854
    }
 
855
 
 
856
    [Test]
 
857
    public void ParseWithPrecendingComments()
 
858
    {
 
859
      string json = @"/* blah */ {'hi':'hi!'}";
 
860
      JObject o = JObject.Parse(json);
 
861
      Assert.AreEqual("hi!", (string)o["hi"]);
 
862
 
 
863
      json = @"/* blah */ ['hi!']";
 
864
      JArray a = JArray.Parse(json);
 
865
      Assert.AreEqual("hi!", (string)a[0]);
 
866
    }
 
867
  }
 
868
}
 
 
b'\\ No newline at end of file'