Json.NET
Code Coverage Statistics for Source File

Newtonsoft.Json.Tests\Linq\LinqToJsonTest.cs

Symbol Coverage: 98.37% (181 of 184)

Branch Coverage: 92.68% (38 of 41)

Cyclomatic Complexity Avg: 1.51 Max:11

Code Lines: 515


L V Source
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.Linq;
29
using System.Text;
30
using NUnit.Framework;
31
using Newtonsoft.Json.Linq;
32
using System.Xml;
33
using System.IO;
34
using Newtonsoft.Json.Converters;
35
using Newtonsoft.Json.Tests.TestObjects;
36

  
37
namespace Newtonsoft.Json.Tests.Linq
38
{
39
  public class LinqToJsonTest : TestFixtureBase
40
  {
41
    [Test]
42
    public void DoubleValue()
43
    {
44
 1
      JArray j = JArray.Parse("[-1E+4,100.0e-2]");
45

  
46
 1
      double value = (double)j[0];
47
 1
      Assert.AreEqual(-10000d, value);
48

  
49
 1
      value = (double)j[1];
50
 1
      Assert.AreEqual(1d, value);
51
 1
    }
52

  
53
    [Test]
54
    public void Manual()
55
    {
56
 1
      JArray array = new JArray();
57
 1
      JValue text = new JValue("Manual text");
58
 1
      JValue date = new JValue(new DateTime(2000, 5, 23));
59

  
60
 1
      array.Add(text);
61
 1
      array.Add(date);
62

  
63
 1
      string json = array.ToString();
64
      // [
65
      //   "Manual text",
66
      //   "\/Date(958996800000+1200)\/"
67
      // ]
68
 1
    }
69

  
70
    [Test]
71
    public void LinqToJsonDeserialize()
72
    {
73
 1
      JObject o = new JObject(
74
 1
        new JProperty("Name", "John Smith"),
75
 1
        new JProperty("BirthDate", new DateTime(1983, 3, 20))
76
 1
        );
77

  
78
 1
      JsonSerializer serializer = new JsonSerializer();
79
 1
      Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));
80

  
81
      // John Smith
82
 1
      Console.WriteLine(p.Name);
83
 1
    }
84

  
85
    [Test]
86
    public void ObjectParse()
87
    {
88
 1
      string json = @"{
89
 1
        CPU: 'Intel',
90
 1
        Drives: [
91
 1
          'DVD read/writer',
92
 1
          ""500 gigabyte hard drive""
93
 1
        ]
94
 1
      }";
95

  
96
 1
      JObject o = JObject.Parse(json);
97
 1
      IList<JProperty> properties = o.Properties().ToList();
98

  
99
 1
      Assert.AreEqual("CPU", properties[0].Name);
100
 1
      Assert.AreEqual("Intel", (string)properties[0].Value);
101
 1
      Assert.AreEqual("Drives", properties[1].Name);
102

  
103
 1
      JArray list = (JArray)properties[1].Value;
104
 1
      Assert.AreEqual(2, list.Children().Count());
105
 1
      Assert.AreEqual("DVD read/writer", (string)list.Children().ElementAt(0));
106
 1
      Assert.AreEqual("500 gigabyte hard drive", (string)list.Children().ElementAt(1));
107

  
108
 1
      List<object> parameterValues =
109
 1
        (from p in o.Properties()
110
 1
         where p.Value is JValue
111
 1
         select ((JValue)p.Value).Value).ToList();
112

  
113
 1
      Assert.AreEqual(1, parameterValues.Count);
114
 1
      Assert.AreEqual("Intel", parameterValues[0]);
115
 1
    }
116

  
117
    [Test]
118
    public void CreateLongArray()
119
    {
120
 1
      string json = @"[0,1,2,3,4,5,6,7,8,9]";
121

  
122
 1
      JArray a = JArray.Parse(json);
123
 1
      List<int> list = a.Values<int>().ToList();
124

  
125
 1
      List<int> expected = new List<int>() { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
126

  
127
 1
      CollectionAssert.AreEqual(expected, list);
128
 1
    }
129

  
130
    [Test]
131
    public void GoogleSearchAPI()
132
    {
133
      #region GoogleJson
134
 1
      string json = @"{
135
 1
    results:
136
 1
        [
137
 1
            {
138
 1
                GsearchResultClass:""GwebSearch"",
139
 1
                unescapedUrl : ""http://www.google.com/"",
140
 1
                url : ""http://www.google.com/"",
141
 1
                visibleUrl : ""www.google.com"",
142
 1
                cacheUrl : 
143
 1
""http://www.google.com/search?q=cache:zhool8dxBV4J:www.google.com"",
144
 1
                title : ""Google"",
145
 1
                titleNoFormatting : ""Google"",
146
 1
                content : ""Enables users to search the Web, Usenet, and 
147
 1
images. Features include PageRank,   caching and translation of 
148
 1
results, and an option to find similar pages.""
149
 1
            },
150
 1
            {
151
 1
                GsearchResultClass:""GwebSearch"",
152
 1
                unescapedUrl : ""http://news.google.com/"",
153
 1
                url : ""http://news.google.com/"",
154
 1
                visibleUrl : ""news.google.com"",
155
 1
                cacheUrl : 
156
 1
""http://www.google.com/search?q=cache:Va_XShOz_twJ:news.google.com"",
157
 1
                title : ""Google News"",
158
 1
                titleNoFormatting : ""Google News"",
159
 1
                content : ""Aggregated headlines and a search engine of many of the world's news sources.""
160
 1
            },
161
 1
            
162
 1
            {
163
 1
                GsearchResultClass:""GwebSearch"",
164
 1
                unescapedUrl : ""http://groups.google.com/"",
165
 1
                url : ""http://groups.google.com/"",
166
 1
                visibleUrl : ""groups.google.com"",
167
 1
                cacheUrl : 
168
 1
""http://www.google.com/search?q=cache:x2uPD3hfkn0J:groups.google.com"",
169
 1
                title : ""Google Groups"",
170
 1
                titleNoFormatting : ""Google Groups"",
171
 1
                content : ""Enables users to search and browse the Usenet 
172
 1
archives which consist of over 700   million messages, and post new 
173
 1
comments.""
174
 1
            },
175
 1
            
176
 1
            {
177
 1
                GsearchResultClass:""GwebSearch"",
178
 1
                unescapedUrl : ""http://maps.google.com/"",
179
 1
                url : ""http://maps.google.com/"",
180
 1
                visibleUrl : ""maps.google.com"",
181
 1
                cacheUrl : 
182
 1
""http://www.google.com/search?q=cache:dkf5u2twBXIJ:maps.google.com"",
183
 1
                title : ""Google Maps"",
184
 1
                titleNoFormatting : ""Google Maps"",
185
 1
                content : ""Provides directions, interactive maps, and 
186
 1
satellite/aerial imagery of the United   States. Can also search by 
187
 1
keyword such as type of business.""
188
 1
            }
189
 1
        ],
190
 1
        
191
 1
    adResults:
192
 1
        [
193
 1
            {
194
 1
                GsearchResultClass:""GwebSearch.ad"",
195
 1
                title : ""Gartner Symposium/ITxpo"",
196
 1
                content1 : ""Meet brilliant Gartner IT analysts"",
197
 1
                content2 : ""20-23 May 2007- Barcelona, Spain"",
198
 1
                url : 
199
 1
""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="", 
200
 1

  
201
 1
                impressionUrl : 
202
 1
""http://www.google.com/uds/css/ad-indicator-on.gif?ai=BVualExYGRo3hD5ianAPJvejjD8-s6ye7kdTwArbI4gTAlrECEAEYASDXtMMFOAFQubWAjvr_____AWDXw_4EiAEBmAEAyAEBgAIB"", 
203
 1

  
204
 1
                unescapedUrl : 
205
 1
""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="", 
206
 1

  
207
 1
                visibleUrl : ""www.gartner.com""
208
 1
            }
209
 1
        ]
210
 1
}
211
 1
";
212
      #endregion
213

  
214
 1
      JObject o = JObject.Parse(json);
215

  
216
 1
      List<JObject> resultObjects = o["results"].Children<JObject>().ToList();
217

  
218
 1
      Assert.AreEqual(32, resultObjects.Properties().Count());
219

  
220
 1
      Assert.AreEqual(32, resultObjects.Cast<JToken>().Values().Count());
221

  
222
 1
      Assert.AreEqual(4, resultObjects.Cast<JToken>().Values("GsearchResultClass").Count());
223

  
224
 1
      Assert.AreEqual(5, o.PropertyValues().Cast<JArray>().Children().Count());
225

  
226
 1
      List<string> resultUrls = o["results"].Children().Values<string>("url").ToList();
227

  
228
 1
      List<string> expectedUrls = new List<string>() { "http://www.google.com/", "http://news.google.com/", "http://groups.google.com/", "http://maps.google.com/" };
229

  
230
 1
      CollectionAssert.AreEqual(expectedUrls, resultUrls);
231

  
232
 1
      List<JToken> descendants = o.Descendants().ToList();
233
 1
      Assert.AreEqual(89, descendants.Count);
234
 1
    }
235

  
236
    [Test]
237
    public void JTokenToString()
238
    {
239
 1
      string json = @"{
240
 1
  CPU: 'Intel',
241
 1
  Drives: [
242
 1
    'DVD read/writer',
243
 1
    ""500 gigabyte hard drive""
244
 1
  ]
245
 1
}";
246

  
247
 1
      JObject o = JObject.Parse(json);
248

  
249
 1
      Assert.AreEqual(@"{
250
 1
  ""CPU"": ""Intel"",
251
 1
  ""Drives"": [
252
 1
    ""DVD read/writer"",
253
 1
    ""500 gigabyte hard drive""
254
 1
  ]
255
 1
}", o.ToString());
256

  
257
 1
      JArray list = o.Value<JArray>("Drives");
258

  
259
 1
      Assert.AreEqual(@"[
260
 1
  ""DVD read/writer"",
261
 1
  ""500 gigabyte hard drive""
262
 1
]", list.ToString());
263

  
264
 1
      JProperty cpuProperty = o.Property("CPU");
265
 1
      Assert.AreEqual(@"""CPU"": ""Intel""", cpuProperty.ToString());
266

  
267
 1
      JProperty drivesProperty = o.Property("Drives");
268
 1
      Assert.AreEqual(@"""Drives"": [
269
 1
  ""DVD read/writer"",
270
 1
  ""500 gigabyte hard drive""
271
 1
]", drivesProperty.ToString());
272
 1
    }
273

  
274
    [Test]
275
    public void JTokenToStringTypes()
276
    {
277
 1
      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}]}";
278

  
279
 1
      JObject o = JObject.Parse(json);
280

  
281
 1
      Assert.AreEqual(@"""Establised"": new Date(
282
 1
  1264118400000
283
 1
)", o.Property("Establised").ToString());
284
 1
      Assert.AreEqual(@"new Date(
285
 1
  1264118400000
286
 1
)", o.Property("Establised").Value.ToString());
287
 1
      Assert.AreEqual(@"""Width"": 1.1", o.Property("Width").ToString());
288
 1
      Assert.AreEqual(@"1.1", o.Property("Width").Value.ToString());
289
 1
      Assert.AreEqual(@"""Open"": false", o.Property("Open").ToString());
290
 1
      Assert.AreEqual(@"false", o.Property("Open").Value.ToString());
291

  
292
 1
      json = @"[null,undefined]";
293

  
294
 1
      JArray a = JArray.Parse(json);
295
 1
      Assert.AreEqual(@"[
296
 1
  null,
297
 1
  undefined
298
 1
]", a.ToString());
299
 1
      Assert.AreEqual(@"null", a.Children().ElementAt(0).ToString());
300
 1
      Assert.AreEqual(@"undefined", a.Children().ElementAt(1).ToString());
301
 1
    }
302

  
303
    [Test]
304
    public void CreateJTokenTree()
305
    {
306
 1
      JObject o =
307
 1
        new JObject(
308
 1
          new JProperty("Test1", "Test1Value"),
309
 1
          new JProperty("Test2", "Test2Value"),
310
 1
          new JProperty("Test3", "Test3Value"),
311
 1
          new JProperty("Test4", null)
312
 1
        );
313

  
314
 1
      Assert.AreEqual(4, o.Properties().Count());
315

  
316
 1
      Assert.AreEqual(@"{
317
 1
  ""Test1"": ""Test1Value"",
318
 1
  ""Test2"": ""Test2Value"",
319
 1
  ""Test3"": ""Test3Value"",
320
 1
  ""Test4"": null
321
 1
}", o.ToString());
322

  
323
 1
      JArray a =
324
 1
        new JArray(
325
 1
          o,
326
 1
          new DateTime(2000, 10, 10, 0, 0, 0, DateTimeKind.Utc),
327
 1
          55,
328
 1
          new JArray(
329
 1
            "1",
330
 1
            2,
331
 1
            3.0,
332
 1
            new DateTime(4, 5, 6, 7, 8, 9, DateTimeKind.Utc)
333
 1
          ),
334
 1
          new JConstructor(
335
 1
            "ConstructorName",
336
 1
            "param1",
337
 1
            2,
338
 1
            3.0
339
 1
          )
340
 1
        );
341

  
342
 1
      Assert.AreEqual(5, a.Count());
343
 1
      Assert.AreEqual(@"[
344
 1
  {
345
 1
    ""Test1"": ""Test1Value"",
346
 1
    ""Test2"": ""Test2Value"",
347
 1
    ""Test3"": ""Test3Value"",
348
 1
    ""Test4"": null
349
 1
  },
350
 1
  ""\/Date(971136000000)\/"",
351
 1
  55,
352
 1
  [
353
 1
    ""1"",
354
 1
    2,
355
 1
    3.0,
356
 1
    ""\/Date(-62030076711000)\/""
357
 1
  ],
358
 1
  new ConstructorName(
359
 1
    ""param1"",
360
 1
    2,
361
 1
    3.0
362
 1
  )
363
 1
]", a.ToString());
364
 1
    }
365

  
366
    private class Post
367
    {
368
      public string Title { get; set; }
369
      public string Description { get; set; }
370
      public string Link { get; set; }
371
      public IList<string> Categories { get; set; }
372
    }
373

  
374
    private List<Post> GetPosts()
375
    {
376
 3
      return new List<Post>()
377
 3
      {
378
 3
        new Post()
379
 3
        {
380
 3
          Title = "LINQ to JSON beta",
381
 3
          Description = "Annoucing LINQ to JSON",
382
 3
          Link = "http://james.newtonking.com/projects/json-net.aspx",
383
 3
          Categories = new List<string>() { "Json.NET", "LINQ" }
384
 3
        },
385
 3
        new Post()
386
 3
        {
387
 3
          Title = "Json.NET 1.3 + New license + Now on CodePlex",
388
 3
          Description = "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
389
 3
          Link = "http://james.newtonking.com/projects/json-net.aspx",
390
 3
          Categories = new List<string>() { "Json.NET", "CodePlex" }
391
 3
        }
392
 3
      };
393
 3
    }
394

  
395
    [Test]
396
    public void CreateJTokenTreeNested()
397
    {
398
 1
      List<Post> posts = GetPosts();
399

  
400
 1
      JObject rss =
401
 1
        new JObject(
402
 1
          new JProperty("channel",
403
 1
            new JObject(
404
 1
              new JProperty("title", "James Newton-King"),
405
 1
              new JProperty("link", "http://james.newtonking.com"),
406
 1
              new JProperty("description", "James Newton-King's blog."),
407
 1
              new JProperty("item",
408
 1
                new JArray(
409
 1
                  from p in posts
410
 1
                  orderby p.Title
411
 1
                  select new JObject(
412
 1
                    new JProperty("title", p.Title),
413
 1
                    new JProperty("description", p.Description),
414
 1
                    new JProperty("link", p.Link),
415
 1
                    new JProperty("category",
416
 1
                      new JArray(
417
 1
                        from c in p.Categories
418
 1
                        select new JValue(c)))))))));
419

  
420
 1
      Console.WriteLine(rss.ToString());
421

  
422
      //{
423
      //  "channel": {
424
      //    "title": "James Newton-King",
425
      //    "link": "http://james.newtonking.com",
426
      //    "description": "James Newton-King's blog.",
427
      //    "item": [
428
      //      {
429
      //        "title": "Json.NET 1.3 + New license + Now on CodePlex",
430
      //        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
431
      //        "link": "http://james.newtonking.com/projects/json-net.aspx",
432
      //        "category": [
433
      //          "Json.NET",
434
      //          "CodePlex"
435
      //        ]
436
      //      },
437
      //      {
438
      //        "title": "LINQ to JSON beta",
439
      //        "description": "Annoucing LINQ to JSON",
440
      //        "link": "http://james.newtonking.com/projects/json-net.aspx",
441
      //        "category": [
442
      //          "Json.NET",
443
      //          "LINQ"
444
      //        ]
445
      //      }
446
      //    ]
447
      //  }
448
      //}
449

  
450
 1
      var postTitles =
451
 1
        from p in rss["channel"]["item"]
452
 1
        select p.Value<string>("title");
453

  
454
 1
      foreach (var item in postTitles)
455
      {
456
 2
        Console.WriteLine(item);
457
      }
458

  
459
      //LINQ to JSON beta
460
      //Json.NET 1.3 + New license + Now on CodePlex
461

  
462
 1
      var categories =
463
 1
        from c in rss["channel"]["item"].Children()["category"].Values<string>()
464
 1
        group c by c into g
465
 1
        orderby g.Count() descending
466
 1
        select new { Category = g.Key, Count = g.Count() };
467

  
468
 1
      foreach (var c in categories)
469
      {
470
 3
        Console.WriteLine(c.Category + " - Count: " + c.Count);
471
      }
472

  
473
      //Json.NET - Count: 2
474
      //LINQ - Count: 1
475
      //CodePlex - Count: 1
476
 1
    }
477

  
478
    [Test]
479
    public void BasicQuerying()
480
    {
481
 1
      string json = @"{
482
 1
                        ""channel"": {
483
 1
                          ""title"": ""James Newton-King"",
484
 1
                          ""link"": ""http://james.newtonking.com"",
485
 1
                          ""description"": ""James Newton-King's blog."",
486
 1
                          ""item"": [
487
 1
                            {
488
 1
                              ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
489
 1
                              ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
490
 1
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
491
 1
                              ""category"": [
492
 1
                                ""Json.NET"",
493
 1
                                ""CodePlex""
494
 1
                              ]
495
 1
                            },
496
 1
                            {
497
 1
                              ""title"": ""LINQ to JSON beta"",
498
 1
                              ""description"": ""Annoucing LINQ to JSON"",
499
 1
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
500
 1
                              ""category"": [
501
 1
                                ""Json.NET"",
502
 1
                                ""LINQ""
503
 1
                              ]
504
 1
                            }
505
 1
                          ]
506
 1
                        }
507
 1
                      }";
508

  
509
 1
      JObject o = JObject.Parse(json);
510

  
511
 1
      Assert.AreEqual(null, o["purple"]);
512
 1
      Assert.AreEqual(null, o.Value<string>("purple"));
513

  
514
 1
      Assert.IsInstanceOfType(typeof(JArray), o["channel"]["item"]);
515

  
516
 1
      Assert.AreEqual(2, o["channel"]["item"].Children()["title"].Count());
517
 1
      Assert.AreEqual(0, o["channel"]["item"].Children()["monkey"].Count());
518

  
519
 1
      Assert.AreEqual("Json.NET 1.3 + New license + Now on CodePlex", (string)o["channel"]["item"][0]["title"]);
520

  
521
 1
      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());
522
 1
    }
523

  
524
    [Test]
525
    [ExpectedException(typeof(ArgumentException), ExpectedMessage = "Accessed JObject values with invalid key value: 0. Object property name expected.")]
526
    public void JObjectIntIndex()
527
    {
528
 1
      JObject o = new JObject();
529
 1
      Assert.AreEqual(null, o[0]);
530
 0
    }
531

  
532
    [Test]
533
    [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Accessed JArray values with invalid key value: ""purple"". Array position index expected.")]
534
    public void JArrayStringIndex()
535
    {
536
 1
      JArray a = new JArray();
537
 1
      Assert.AreEqual(null, a["purple"]);
538
 0
    }
539

  
540
    [Test]
541
    [ExpectedException(typeof(ArgumentException), ExpectedMessage = @"Accessed JConstructor values with invalid key value: ""purple"". Argument position index expected.")]
542
    public void JConstructorStringIndex()
543
    {
544
 1
      JConstructor c = new JConstructor("ConstructorValue");
545
 1
      Assert.AreEqual(null, c["purple"]);
546
 0
    }
547

  
548
#if !PocketPC && !NET20
549
    [Test]
550
    public void ToStringJsonConverter()
551
    {
552
 1
      JObject o =
553
 1
        new JObject(
554
 1
          new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)),
555
 1
          new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))),
556
 1
          new JProperty("Test3", "Test3Value"),
557
 1
          new JProperty("Test4", null)
558
 1
        );
559

  
560
 1
      JsonSerializer serializer = new JsonSerializer();
561
 1
      serializer.Converters.Add(new JavaScriptDateTimeConverter());
562
 1
      StringWriter sw = new StringWriter();
563
 1
      JsonWriter writer = new JsonTextWriter(sw);
564
 1
      writer.Formatting = Formatting.Indented;
565
 1
      serializer.Serialize(writer, o);
566

  
567
 1
      string json = sw.ToString();
568

  
569
 1
      Assert.AreEqual(@"{
570
 1
  ""Test1"": new Date(
571
 1
    971586305000
572
 1
  ),
573
 1
  ""Test2"": new Date(
574
 1
    971546045000
575
 1
  ),
576
 1
  ""Test3"": ""Test3Value"",
577
 1
  ""Test4"": null
578
 1
}", json);
579
 1
    }
580

  
581
    [Test]
582
    public void DateTimeOffset()
583
    {
584
 1
      List<DateTimeOffset> testDates = new List<DateTimeOffset> {
585
 1
        new DateTimeOffset(new DateTime(100, 1, 1, 1, 1, 1, DateTimeKind.Utc)),
586
 1
        new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.Zero),
587
 1
        new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(13)),
588
 1
        new DateTimeOffset(2000, 1, 1, 1, 1, 1, TimeSpan.FromHours(-3.5)),
589
 1
      };
590

  
591
 1
      JsonSerializer jsonSerializer = new JsonSerializer();
592

  
593
      JTokenWriter jsonWriter;
594
 1
      using (jsonWriter = new JTokenWriter())
595
      {
596
 1
        jsonSerializer.Serialize(jsonWriter, testDates);
597
      }
598

  
599
 1
      Assert.AreEqual(4, jsonWriter.Token.Children().Count());
600
 1
    }
601
#endif
602

  
603
    [Test]
604
    public void FromObject()
605
    {
606
 1
      List<Post> posts = GetPosts();
607

  
608
 1
      JObject o = JObject.FromObject(new
609
 1
      {
610
 1
        channel = new
611
 1
        {
612
 1
          title = "James Newton-King",
613
 1
          link = "http://james.newtonking.com",
614
 1
          description = "James Newton-King's blog.",
615
 1
          item =
616
 1
              from p in posts
617
 1
              orderby p.Title
618
 1
              select new
619
 1
              {
620
 1
                title = p.Title,
621
 1
                description = p.Description,
622
 1
                link = p.Link,
623
 1
                category = p.Categories
624
 1
              }
625
 1
        }
626
 1
      });
627

  
628
 1
      Console.WriteLine(o.ToString());
629
 1
      Assert.IsInstanceOfType(typeof(JObject), o);
630
 1
      Assert.IsInstanceOfType(typeof(JObject), o["channel"]);
631
 1
      Assert.AreEqual("James Newton-King", (string)o["channel"]["title"]);
632
 1
      Assert.AreEqual(2, o["channel"]["item"].Children().Count());
633

  
634
 1
      JArray a = JArray.FromObject(new List<int>() { 0, 1, 2, 3, 4 });
635
 1
      Assert.IsInstanceOfType(typeof(JArray), a);
636
 1
      Assert.AreEqual(5, a.Count());
637
 1
    }
638

  
639
    [Test]
640
    public void FromAnonDictionary()
641
    {
642
 1
      List<Post> posts = GetPosts();
643

  
644
 1
      JObject o = JObject.FromObject(new
645
 1
      {
646
 1
        channel = new Dictionary<string, object>
647
 1
        {
648
 1
          { "title", "James Newton-King" },
649
 1
          { "link", "http://james.newtonking.com" },
650
 1
          { "description", "James Newton-King's blog." },
651
 1
          { "item", 
652
 1
                  (from p in posts
653
 1
                  orderby p.Title
654
 1
                  select new
655
 1
                  {
656
 1
                    title = p.Title,
657
 1
                    description = p.Description,
658
 1
                    link = p.Link,
659
 1
                    category = p.Categories
660
 1
                  })
661
 1
          }
662
 1
        }
663
 1
      });
664

  
665
 1
      Console.WriteLine(o.ToString());
666
 1
      Assert.IsInstanceOfType(typeof(JObject), o);
667
 1
      Assert.IsInstanceOfType(typeof(JObject), o["channel"]);
668
 1
      Assert.AreEqual("James Newton-King", (string)o["channel"]["title"]);
669
 1
      Assert.AreEqual(2, o["channel"]["item"].Children().Count());
670

  
671
 1
      JArray a = JArray.FromObject(new List<int>() { 0, 1, 2, 3, 4 });
672
 1
      Assert.IsInstanceOfType(typeof(JArray), a);
673
 1
      Assert.AreEqual(5, a.Count());
674
 1
    }
675

  
676
    [Test]
677
    public void AsJEnumerable()
678
    {
679
 1
      JObject o = null;
680
 1
      IJEnumerable<JToken> enumerable = null;
681

  
682
 1
      enumerable = o.AsJEnumerable();
683
 1
      Assert.IsNull(enumerable);
684
    
685
 1
      o =
686
 1
        new JObject(
687
 1
          new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)),
688
 1
          new JProperty("Test2", "Test2Value"),
689
 1
          new JProperty("Test3", null)
690
 1
        );
691

  
692
 1
      enumerable = o.AsJEnumerable();
693
 1
      Assert.IsNotNull(enumerable);
694
 1
      Assert.AreEqual(o, enumerable);
695

  
696
 1
      DateTime d = enumerable["Test1"].Value<DateTime>();
697

  
698
 1
      Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), d);
699
 1
    }
700

  
701
    [Test]
702
    public void ChildrenExtension()
703
    {
704
 1
      string json = @"[
705
 1
                        {
706
 1
                          ""title"": ""James Newton-King"",
707
 1
                          ""link"": ""http://james.newtonking.com"",
708
 1
                          ""description"": ""James Newton-King's blog."",
709
 1
                          ""item"": [
710
 1
                            {
711
 1
                              ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
712
 1
                              ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
713
 1
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
714
 1
                              ""category"": [
715
 1
                                ""Json.NET"",
716
 1
                                ""CodePlex""
717
 1
                              ]
718
 1
                            },
719
 1
                            {
720
 1
                              ""title"": ""LINQ to JSON beta"",
721
 1
                              ""description"": ""Annoucing LINQ to JSON"",
722
 1
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
723
 1
                              ""category"": [
724
 1
                                ""Json.NET"",
725
 1
                                ""LINQ""
726
 1
                              ]
727
 1
                            }
728
 1
                          ]
729
 1
                        },
730
 1
                        {
731
 1
                          ""title"": ""James Newton-King"",
732
 1
                          ""link"": ""http://james.newtonking.com"",
733
 1
                          ""description"": ""James Newton-King's blog."",
734
 1
                          ""item"": [
735
 1
                            {
736
 1
                              ""title"": ""Json.NET 1.3 + New license + Now on CodePlex"",
737
 1
                              ""description"": ""Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex"",
738
 1
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
739
 1
                              ""category"": [
740
 1
                                ""Json.NET"",
741
 1
                                ""CodePlex""
742
 1
                              ]
743
 1
                            },
744
 1
                            {
745
 1
                              ""title"": ""LINQ to JSON beta"",
746
 1
                              ""description"": ""Annoucing LINQ to JSON"",
747
 1
                              ""link"": ""http://james.newtonking.com/projects/json-net.aspx"",
748
 1
                              ""category"": [
749
 1
                                ""Json.NET"",
750
 1
                                ""LINQ""
751
 1
                              ]
752
 1
                            }
753
 1
                          ]
754
 1
                        }
755
 1
                      ]";
756

  
757
 1
      JArray o = JArray.Parse(json);
758

  
759
 1
      Assert.AreEqual(4, o.Children()["item"].Children()["title"].Count());
760
 1
      CollectionAssert.AreEqual(new string[]
761
 1
        {
762
 1
          "Json.NET 1.3 + New license + Now on CodePlex",
763
 1
          "LINQ to JSON beta",
764
 1
          "Json.NET 1.3 + New license + Now on CodePlex",
765
 1
          "LINQ to JSON beta"
766
 1
        },
767
 1
        o.Children()["item"].Children()["title"].Values<string>().ToArray());
768
 1
    }
769
  }
770
}