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

« back to all changes in this revision

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

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
ļ»æ#region License
 
2
// Copyright (c) 2007 James Newton-King
 
3
//
 
4
// Permission is hereby granted, free of charge, to any person
 
5
// obtaining a copy of this software and associated documentation
 
6
// files (the "Software"), to deal in the Software without
 
7
// restriction, including without limitation the rights to use,
 
8
// copy, modify, merge, publish, distribute, sublicense, and/or sell
 
9
// copies of the Software, and to permit persons to whom the
 
10
// Software is furnished to do so, subject to the following
 
11
// conditions:
 
12
//
 
13
// The above copyright notice and this permission notice shall be
 
14
// included in all copies or substantial portions of the Software.
 
15
//
 
16
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 
17
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 
18
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 
19
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 
20
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 
21
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 
22
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 
23
// OTHER DEALINGS IN THE SOFTWARE.
 
24
#endregion
 
25
 
 
26
#if !(NET35 || NET20 || PORTABLE)
 
27
using System;
 
28
using System.Collections.Generic;
 
29
using System.ComponentModel;
 
30
using System.Dynamic;
 
31
using System.IO;
 
32
using System.Linq;
 
33
using System.Runtime.Serialization;
 
34
using System.Text;
 
35
using Newtonsoft.Json.Converters;
 
36
using Newtonsoft.Json.Linq;
 
37
#if !NETFX_CORE
 
38
using NUnit.Framework;
 
39
#else
 
40
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
 
41
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
 
42
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
 
43
#endif
 
44
using Newtonsoft.Json.Serialization;
 
45
using Newtonsoft.Json.Tests.TestObjects;
 
46
using Newtonsoft.Json.Utilities;
 
47
using System.Globalization;
 
48
using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs;
 
49
using File = System.IO.File;
 
50
 
 
51
namespace Newtonsoft.Json.Tests.Documentation
 
52
{
 
53
  public static class File
 
54
  {
 
55
    public static StreamReader OpenText(string path)
 
56
    {
 
57
      return null;
 
58
    }
 
59
  }
 
60
 
 
61
  public class LinqToJsonTests
 
62
  {
 
63
    public void LinqToJsonBasic()
 
64
    {
 
65
      #region LinqToJsonBasic
 
66
      JObject o = JObject.Parse(@"{
 
67
        'CPU': 'Intel',
 
68
        'Drives': [
 
69
          'DVD read/writer',
 
70
          '500 gigabyte hard drive'
 
71
        ]
 
72
      }");
 
73
 
 
74
      string cpu = (string)o["CPU"];
 
75
      // Intel
 
76
 
 
77
      string firstDrive = (string)o["Drives"][0];
 
78
      // DVD read/writer
 
79
 
 
80
      IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
 
81
      // DVD read/writer
 
82
      // 500 gigabyte hard drive
 
83
      #endregion
 
84
    }
 
85
 
 
86
    public void LinqToJsonCreateNormal()
 
87
    {
 
88
      #region LinqToJsonCreateNormal
 
89
      JArray array = new JArray();
 
90
      JValue text = new JValue("Manual text");
 
91
      JValue date = new JValue(new DateTime(2000, 5, 23));
 
92
 
 
93
      array.Add(text);
 
94
      array.Add(date);
 
95
 
 
96
      string json = array.ToString();
 
97
      // [
 
98
      //   "Manual text",
 
99
      //   "2000-05-23T00:00:00"
 
100
      // ]
 
101
      #endregion
 
102
    }
 
103
 
 
104
    public class Post
 
105
    {
 
106
      public string Title { get; set; }
 
107
      public string Description { get; set; }
 
108
      public string Link { get; set; }
 
109
      public IList<string> Categories { get; set; }
 
110
    }
 
111
 
 
112
    private List<Post> GetPosts()
 
113
    {
 
114
      return null;
 
115
    }
 
116
 
 
117
    public void LinqToJsonCreateDeclaratively()
 
118
    {
 
119
      #region LinqToJsonCreateDeclaratively
 
120
      List<Post> posts = GetPosts();
 
121
 
 
122
      JObject rss =
 
123
        new JObject(
 
124
          new JProperty("channel",
 
125
            new JObject(
 
126
              new JProperty("title", "James Newton-King"),
 
127
              new JProperty("link", "http://james.newtonking.com"),
 
128
              new JProperty("description", "James Newton-King's blog."),
 
129
              new JProperty("item",
 
130
                new JArray(
 
131
                  from p in posts
 
132
                  orderby p.Title
 
133
                  select new JObject(
 
134
                    new JProperty("title", p.Title),
 
135
                    new JProperty("description", p.Description),
 
136
                    new JProperty("link", p.Link),
 
137
                    new JProperty("category",
 
138
                      new JArray(
 
139
                        from c in p.Categories
 
140
                        select new JValue(c)))))))));
 
141
 
 
142
      Console.WriteLine(rss.ToString());
 
143
 
 
144
      //{
 
145
      //  "channel": {
 
146
      //    "title": "James Newton-King",
 
147
      //    "link": "http://james.newtonking.com",
 
148
      //    "description": "James Newton-King's blog.",
 
149
      //    "item": [
 
150
      //      {
 
151
      //        "title": "Json.NET 1.3 + New license + Now on CodePlex",
 
152
      //        "description": "Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex",
 
153
      //        "link": "http://james.newtonking.com/projects/json-net.aspx",
 
154
      //        "category": [
 
155
      //          "Json.NET",
 
156
      //          "CodePlex"
 
157
      //        ]
 
158
      //      },
 
159
      //      {
 
160
      //        "title": "LINQ to JSON beta",
 
161
      //        "description": "Annoucing LINQ to JSON",
 
162
      //        "link": "http://james.newtonking.com/projects/json-net.aspx",
 
163
      //        "category": [
 
164
      //          "Json.NET",
 
165
      //          "LINQ"
 
166
      //        ]
 
167
      //      }
 
168
      //    ]
 
169
      //  }
 
170
      //}
 
171
      #endregion
 
172
    }
 
173
 
 
174
    public void LinqToJsonCreateFromObject()
 
175
    {
 
176
      List<Post> posts = null;
 
177
 
 
178
      #region LinqToJsonCreateFromObject
 
179
      JObject o = JObject.FromObject(new
 
180
      {
 
181
        channel = new
 
182
        {
 
183
          title = "James Newton-King",
 
184
          link = "http://james.newtonking.com",
 
185
          description = "James Newton-King's blog.",
 
186
          item =
 
187
              from p in posts
 
188
              orderby p.Title
 
189
              select new
 
190
              {
 
191
                title = p.Title,
 
192
                description = p.Description,
 
193
                link = p.Link,
 
194
                category = p.Categories
 
195
              }
 
196
        }
 
197
      });
 
198
      #endregion
 
199
    }
 
200
 
 
201
    public void LinqToJsonCreateParse()
 
202
    {
 
203
      #region LinqToJsonCreateParse
 
204
      string json = @"{
 
205
        CPU: 'Intel',
 
206
        Drives: [
 
207
          'DVD read/writer',
 
208
          '500 gigabyte hard drive'
 
209
        ]
 
210
      }";
 
211
 
 
212
      JObject o = JObject.Parse(json);
 
213
      #endregion
 
214
    }
 
215
 
 
216
    public void LinqToJsonCreateParseArray()
 
217
    {
 
218
      #region LinqToJsonCreateParseArray
 
219
      string json = @"[
 
220
        'Small',
 
221
        'Medium',
 
222
        'Large'
 
223
      ]";
 
224
 
 
225
      JArray a = JArray.Parse(json);
 
226
      #endregion
 
227
    }
 
228
 
 
229
    public void LinqToJsonReadObject()
 
230
    {
 
231
      #region LinqToJsonReadObject
 
232
      using (StreamReader reader = File.OpenText(@"c:\person.json"))
 
233
      {
 
234
        JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
 
235
        // do stuff
 
236
      }
 
237
      #endregion
 
238
    }
 
239
 
 
240
    public void LinqToJsonSimpleQuerying()
 
241
    {
 
242
      #region LinqToJsonSimpleQuerying
 
243
      string json = @"{
 
244
        'channel': {
 
245
          'title': 'James Newton-King',
 
246
          'link': 'http://james.newtonking.com',
 
247
          'description': 'James Newton-King's blog.',
 
248
          'item': [
 
249
            {
 
250
              'title': 'Json.NET 1.3 + New license + Now on CodePlex',
 
251
              'description': 'Annoucing the release of Json.NET 1.3, the MIT license and the source being available on CodePlex',
 
252
              'link': 'http://james.newtonking.com/projects/json-net.aspx',
 
253
              'categories': [
 
254
                'Json.NET',
 
255
                'CodePlex'
 
256
              ]
 
257
            },
 
258
            {
 
259
              'title': 'LINQ to JSON beta',
 
260
              'description': 'Annoucing LINQ to JSON',
 
261
              'link': 'http://james.newtonking.com/projects/json-net.aspx',
 
262
              'categories': [
 
263
                'Json.NET',
 
264
                'LINQ'
 
265
              ]
 
266
            }
 
267
          ]
 
268
        }
 
269
      }";
 
270
 
 
271
      JObject rss = JObject.Parse(json);
 
272
 
 
273
      string rssTitle = (string)rss["channel"]["title"];
 
274
      // James Newton-King
 
275
 
 
276
      string itemTitle = (string)rss["channel"]["item"][0]["title"];
 
277
      // Json.NET 1.3 + New license + Now on CodePlex
 
278
 
 
279
      JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
 
280
      // ["Json.NET", "CodePlex"]
 
281
 
 
282
      IList<string> categoriesText = categories.Select(c => (string)c).ToList();
 
283
      // Json.NET
 
284
      // CodePlex
 
285
      #endregion
 
286
    }
 
287
 
 
288
    public void LinqToJsonQuerying()
 
289
    {
 
290
      JObject rss = new JObject();
 
291
 
 
292
      #region LinqToJsonQuerying
 
293
      var postTitles =
 
294
        from p in rss["channel"]["item"].Children()
 
295
        select (string)p["title"];
 
296
 
 
297
      foreach (var item in postTitles)
 
298
      {
 
299
        Console.WriteLine(item);
 
300
      }
 
301
 
 
302
      //LINQ to JSON beta
 
303
      //Json.NET 1.3 + New license + Now on CodePlex
 
304
 
 
305
      var categories =
 
306
        from c in rss["channel"]["item"].Children()["category"].Values<string>()
 
307
        group c by c into g
 
308
        orderby g.Count() descending
 
309
        select new { Category = g.Key, Count = g.Count() };
 
310
 
 
311
      foreach (var c in categories)
 
312
      {
 
313
        Console.WriteLine(c.Category + " - Count: " + c.Count);
 
314
      }
 
315
 
 
316
      //Json.NET - Count: 2
 
317
      //LINQ - Count: 1
 
318
      //CodePlex - Count: 1
 
319
      #endregion
 
320
    }
 
321
 
 
322
    #region LinqToJsonDeserializeObject
 
323
    public class Shortie
 
324
    {
 
325
      public string Original { get; set; }
 
326
      public string Shortened { get; set; }
 
327
      public string Short { get; set; }
 
328
      public ShortieException Error { get; set; }
 
329
    }
 
330
 
 
331
    public class ShortieException
 
332
    {
 
333
      public int Code { get; set; }
 
334
      public string ErrorMessage { get; set; }
 
335
    }
 
336
    #endregion
 
337
 
 
338
    public void LinqToJsonDeserializeExample()
 
339
    {
 
340
      #region LinqToJsonDeserializeExample
 
341
      string jsonText = @"{
 
342
        'short': {
 
343
          'original': 'http://www.foo.com/',
 
344
          'short': 'krehqk',
 
345
          'error': {
 
346
            'code':0,
 
347
            'msg':'No action taken'
 
348
          }
 
349
      }";
 
350
 
 
351
      JObject json = JObject.Parse(jsonText);
 
352
 
 
353
      Shortie shortie = new Shortie
 
354
      {
 
355
        Original = (string)json["short"]["original"],
 
356
        Short = (string)json["short"]["short"],
 
357
        Error = new ShortieException
 
358
        {
 
359
          Code = (int)json["short"]["error"]["code"],
 
360
          ErrorMessage = (string)json["short"]["error"]["msg"]
 
361
        }
 
362
      };
 
363
 
 
364
      Console.WriteLine(shortie.Original);
 
365
      // http://www.foo.com/
 
366
 
 
367
      Console.WriteLine(shortie.Error.ErrorMessage);
 
368
      // No action taken
 
369
      #endregion
 
370
    }
 
371
 
 
372
    public void SelectTokenSimple()
 
373
    {
 
374
      JObject o = new JObject();
 
375
 
 
376
      #region SelectTokenSimple
 
377
      string name = (string)o.SelectToken("Manufacturers[0].Name");
 
378
      #endregion
 
379
    }
 
380
 
 
381
    public void SelectTokenComplex()
 
382
    {
 
383
      #region SelectTokenComplex
 
384
      JObject o = JObject.Parse(@"{
 
385
        'Stores': [
 
386
          'Lambton Quay',
 
387
          'Willis Street'
 
388
        ],
 
389
        'Manufacturers': [
 
390
          {
 
391
            'Name': 'Acme Co',
 
392
            'Products': [
 
393
              {
 
394
                'Name': 'Anvil',
 
395
                'Price': 50
 
396
              }
 
397
            ]
 
398
          },
 
399
          {
 
400
            'Name': 'Contoso',
 
401
            'Products': [
 
402
              {
 
403
                'Name': 'Elbow Grease',
 
404
                'Price': 99.95
 
405
              },
 
406
              {
 
407
                'Name': 'Headlight Fluid',
 
408
                'Price': 4
 
409
              }
 
410
            ]
 
411
          }
 
412
        ]
 
413
      }");
 
414
 
 
415
      string name = (string)o.SelectToken("Manufacturers[0].Name");
 
416
      // Acme Co
 
417
 
 
418
      decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
 
419
      // 50
 
420
 
 
421
      string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
 
422
      // Elbow Grease
 
423
      #endregion
 
424
    }
 
425
 
 
426
    public void SelectTokenLinq()
 
427
    {
 
428
      JObject o = new JObject();
 
429
 
 
430
      #region SelectTokenLinq
 
431
      IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
 
432
      // Lambton Quay
 
433
      // Willis Street
 
434
 
 
435
      IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
 
436
      // null
 
437
      // Headlight Fluid
 
438
 
 
439
      decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
 
440
      // 149.95
 
441
      #endregion
 
442
    }
 
443
  }
 
444
}
 
445
#endif
 
 
b'\\ No newline at end of file'