-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathLinqToJsonTests.cs
580 lines (495 loc) · 15.7 KB
/
LinqToJsonTests.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
// Copyright (c) 2007 James Newton-King. All rights reserved.
// Use of this source code is governed by The MIT License,
// as found in the license.md file.
// ReSharper disable UnusedVariable
// ReSharper disable PossibleMultipleEnumeration
namespace Argon.Tests.Documentation;
public class LinqToJsonTests : TestFixtureBase
{
[Fact]
public void LinqToJsonBasic()
{
#region LinqToJsonBasic
var o = JObject.Parse(
"""
{
'CPU': 'Intel',
'Drives': [
'DVD read/writer',
'500 gigabyte hard drive'
]
}
""");
var cpu = (string) o["CPU"];
// Intel
var firstDrive = (string) o["Drives"][0];
// DVD read/writer
var allDrives = o["Drives"]
.Select(t => (string) t)
.ToList();
// DVD read/writer
// 500 gigabyte hard drive
#endregion
}
[Fact]
public void LinqToJsonCreateNormal()
{
#region LinqToJsonCreateNormal
var array = new JArray();
var text = new JValue("Manual text");
var date = new JValue(new DateTime(2000, 5, 23));
array.Add(text);
array.Add(date);
var json = array.ToString();
// [
// "Manual text",
// "2000-05-23T00:00:00"
// ]
#endregion
}
public class Post
{
public string Title { get; set; }
public string Description { get; set; }
public string Link { get; set; }
public IList<string> Categories { get; set; }
}
static List<Post> GetPosts() => [];
[Fact]
public void LinqToJsonCreateDeclaratively()
{
#region LinqToJsonCreateDeclaratively
var posts = GetPosts();
var rss =
new JObject(
new JProperty("channel",
new JObject(
new JProperty("title", "James Newton-King"),
new JProperty("link", "http://james.newtonking.com"),
new JProperty("description", "James Newton-King's blog."),
new JProperty("item",
new JArray(
from p in posts
orderby p.Title
select new JObject(
new JProperty("title", p.Title),
new JProperty("description", p.Description),
new JProperty("link", p.Link),
new JProperty("category",
new JArray(
from c in p.Categories
select new JValue(c)))))))));
Console.WriteLine(rss.ToString());
//{
// "channel": {
// "title": "James Newton-King",
// "link": "http://james.newtonking.com",
// "description": "James Newton-King\'s blog.",
// "item": [
// {
// "title": "Json.NET 1.3 + New license + Now on CodePlex",
// "description": "Announcing the release of Json.NET 1.3, the MIT license and being available on CodePlex",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "CodePlex"
// ]
// },
// {
// "title": "LINQ to JSON beta",
// "description": "Announcing LINQ to JSON",
// "link": "http://james.newtonking.com/projects/json-net.aspx",
// "category": [
// "Json.NET",
// "LINQ"
// ]
// }
// ]
// }
//}
#endregion
}
[Fact]
public void LinqToJsonCreateFromObject()
{
var posts = GetPosts();
#region LinqToJsonCreateFromObject
var o = JObject.FromObject(new
{
channel = new
{
title = "James Newton-King",
link = "http://james.newtonking.com",
description = "James Newton-King's blog.",
item =
from p in posts
orderby p.Title
select new
{
title = p.Title,
description = p.Description,
link = p.Link,
category = p.Categories
}
}
});
#endregion
}
[Fact]
public void LinqToJsonCreateParse()
{
#region LinqToJsonCreateParse
var json = """
{
CPU: 'Intel',
Drives: [
'DVD read/writer',
'500 gigabyte hard drive'
]
}
""";
var o = JObject.Parse(json);
#endregion
}
[Fact]
public void LinqToJsonCreateParseArray()
{
#region LinqToJsonCreateParseArray
var json = """
[
'Small',
'Medium',
'Large'
]
""";
var a = JArray.Parse(json);
#endregion
}
public static class File
{
public static StreamReader OpenText(string path) =>
new(new MemoryStream("{}"u8.ToArray()));
}
[Fact]
public void LinqToJsonReadObject()
{
#region LinqToJsonReadObject
using var reader = File.OpenText(@"c:\person.json");
var o = (JObject) JToken.ReadFrom(new JsonTextReader(reader));
// do stuff
#endregion
}
[Fact]
public void LinqToJsonSimpleQuerying()
{
#region LinqToJsonSimpleQuerying
var json = """
{
'channel': {
'title': 'James Newton-King',
'link': 'http://james.newtonking.com',
'description': 'James Newton-King\'s blog.',
'item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
'description': 'Announcing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Announcing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'LINQ'
]
}
]
}
}
""";
var rss = JObject.Parse(json);
var rssTitle = (string) rss["channel"]["title"];
// James Newton-King
var itemTitle = (string) rss["channel"]["item"][0]["title"];
// Json.NET 1.3 + New license + Now on CodePlex
var categories = (JArray) rss["channel"]["item"][0]["categories"];
// ["Json.NET", "CodePlex"]
var categoriesText = categories
.Select(c => (string) c)
.ToList();
// Json.NET
// CodePlex
#endregion
}
[Fact]
public void LinqToJsonQuerying()
{
var rss = JObject.Parse(
"""
{
'channel': {
'title': 'James Newton-King',
'link': 'http://james.newtonking.com',
'description': 'James Newton-King\'s blog.',
'item': [
{
'title': 'Json.NET 1.3 + New license + Now on CodePlex',
'description': 'Announcing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'CodePlex'
]
},
{
'title': 'LINQ to JSON beta',
'description': 'Announcing LINQ to JSON',
'link': 'http://james.newtonking.com/projects/json-net.aspx',
'categories': [
'Json.NET',
'LINQ'
]
}
]
}
}
""");
#region LinqToJsonQuerying
var postTitles =
(
from p in rss["channel"]["item"]
select (string) p["title"]
)
.ToList();
foreach (var item in postTitles)
{
Console.WriteLine(item);
}
//LINQ to JSON beta
//Json.NET 1.3 + New license + Now on CodePlex
var categories =
(
from c in rss["channel"]["item"]
.SelectMany(_ => _["categories"])
.Values<string>()
group c by c
into g
orderby g.Count() descending
select new
{
Category = g.Key,
Count = g.Count()
}
)
.ToList();
foreach (var c in categories)
{
Console.WriteLine($"{c.Category} - Count: {c.Count}");
}
//Json.NET - Count: 2
//LINQ - Count: 1
//CodePlex - Count: 1
#endregion
Assert.Equal(2, postTitles.Count);
Assert.Equal(3, categories.Count);
}
#region LinqToJsonDeserializeObject
public class Shortie
{
public string Original { get; set; }
public string Shortened { get; set; }
public string Short { get; set; }
public ShortieException Error { get; set; }
}
public class ShortieException
{
public int Code { get; set; }
public string ErrorMessage { get; set; }
}
#endregion
[Fact]
public void LinqToJsonDeserializeExample()
{
#region LinqToJsonDeserializeExample
var jsonText = """
{
'short': {
'original': 'http://www.foo.com/',
'short': 'krehqk',
'error': {
'code': 0,
'msg': 'No action taken'
}
}
}
""";
var json = JObject.Parse(jsonText);
var shortie = new Shortie
{
Original = (string) json["short"]["original"],
Short = (string) json["short"]["short"],
Error = new()
{
Code = (int) json["short"]["error"]["code"],
ErrorMessage = (string) json["short"]["error"]["msg"]
}
};
Console.WriteLine(shortie.Original);
// http://www.foo.com/
Console.WriteLine(shortie.Error.ErrorMessage);
// No action taken
#endregion
Assert.Equal("http://www.foo.com/", shortie.Original);
Assert.Equal("No action taken", shortie.Error.ErrorMessage);
}
[Fact]
public void SelectTokenSimple()
{
var o = JObject.Parse(
"""
{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}
""");
#region SelectTokenSimple
var name = (string) o.SelectToken("Manufacturers[0].Name");
#endregion
Assert.Equal("Acme Co", name);
}
[Fact]
public void SelectTokenComplex()
{
#region SelectTokenComplex
var o = JObject.Parse(
"""
{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}
""");
var name = (string) o.SelectToken("Manufacturers[0].Name");
// Acme Co
var productPrice = (decimal) o.SelectToken("Manufacturers[0].Products[0].Price");
// 50
var productName = (string) o.SelectToken("Manufacturers[1].Products[0].Name");
// Elbow Grease
#endregion
Assert.Equal("Acme Co", name);
Assert.Equal(50m, productPrice);
Assert.Equal("Elbow Grease", productName);
}
[Fact]
public void SelectTokenLinq()
{
var o = JObject.Parse(
"""
{
'Stores': [
'Lambton Quay',
'Willis Street'
],
'Manufacturers': [
{
'Name': 'Acme Co',
'Products': [
{
'Name': 'Anvil',
'Price': 50
}
]
},
{
'Name': 'Contoso',
'Products': [
{
'Name': 'Elbow Grease',
'Price': 99.95
},
{
'Name': 'Headlight Fluid',
'Price': 4
}
]
}
]
}
""");
#region SelectTokenLinq
var storeNames = o
.SelectToken("Stores")
.Select(s => (string) s)
.ToList();
// Lambton Quay
// Willis Street
var firstProductNames = o["Manufacturers"]
.Select(m => (string) m.SelectToken("Products[1].Name"))
.ToList();
// null
// Headlight Fluid
var totalPrice = o["Manufacturers"]
.Sum(m => (decimal) m.SelectToken("Products[0].Price"));
// 149.95
#endregion
Assert.Equal(2, storeNames.Count);
Assert.Equal(2, firstProductNames.Count);
Assert.Equal(149.95m, totalPrice);
}
}