2
// Copyright (c) 2007 James Newton-King
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
13
// The above copyright notice and this permission notice shall be
14
// included in all copies or substantial portions of the Software.
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.
26
#if !(NET35 || NET20 || PORTABLE)
28
using System.Collections.Generic;
29
using System.ComponentModel;
33
using System.Runtime.Serialization;
35
using Newtonsoft.Json.Converters;
36
using Newtonsoft.Json.Linq;
38
using NUnit.Framework;
40
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
41
using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute;
42
using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute;
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;
51
namespace Newtonsoft.Json.Tests.Documentation
53
public static class File
55
public static StreamReader OpenText(string path)
61
public class LinqToJsonTests
63
public void LinqToJsonBasic()
65
#region LinqToJsonBasic
66
JObject o = JObject.Parse(@"{
70
'500 gigabyte hard drive'
74
string cpu = (string)o["CPU"];
77
string firstDrive = (string)o["Drives"][0];
80
IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
82
// 500 gigabyte hard drive
86
public void LinqToJsonCreateNormal()
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));
96
string json = array.ToString();
99
// "2000-05-23T00:00:00"
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; }
112
private List<Post> GetPosts()
117
public void LinqToJsonCreateDeclaratively()
119
#region LinqToJsonCreateDeclaratively
120
List<Post> posts = GetPosts();
124
new JProperty("channel",
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",
134
new JProperty("title", p.Title),
135
new JProperty("description", p.Description),
136
new JProperty("link", p.Link),
137
new JProperty("category",
139
from c in p.Categories
140
select new JValue(c)))))))));
142
Console.WriteLine(rss.ToString());
146
// "title": "James Newton-King",
147
// "link": "http://james.newtonking.com",
148
// "description": "James Newton-King's blog.",
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",
160
// "title": "LINQ to JSON beta",
161
// "description": "Annoucing LINQ to JSON",
162
// "link": "http://james.newtonking.com/projects/json-net.aspx",
174
public void LinqToJsonCreateFromObject()
176
List<Post> posts = null;
178
#region LinqToJsonCreateFromObject
179
JObject o = JObject.FromObject(new
183
title = "James Newton-King",
184
link = "http://james.newtonking.com",
185
description = "James Newton-King's blog.",
192
description = p.Description,
194
category = p.Categories
201
public void LinqToJsonCreateParse()
203
#region LinqToJsonCreateParse
208
'500 gigabyte hard drive'
212
JObject o = JObject.Parse(json);
216
public void LinqToJsonCreateParseArray()
218
#region LinqToJsonCreateParseArray
225
JArray a = JArray.Parse(json);
229
public void LinqToJsonReadObject()
231
#region LinqToJsonReadObject
232
using (StreamReader reader = File.OpenText(@"c:\person.json"))
234
JObject o = (JObject)JToken.ReadFrom(new JsonTextReader(reader));
240
public void LinqToJsonSimpleQuerying()
242
#region LinqToJsonSimpleQuerying
245
'title': 'James Newton-King',
246
'link': 'http://james.newtonking.com',
247
'description': 'James Newton-King's blog.',
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',
259
'title': 'LINQ to JSON beta',
260
'description': 'Annoucing LINQ to JSON',
261
'link': 'http://james.newtonking.com/projects/json-net.aspx',
271
JObject rss = JObject.Parse(json);
273
string rssTitle = (string)rss["channel"]["title"];
276
string itemTitle = (string)rss["channel"]["item"][0]["title"];
277
// Json.NET 1.3 + New license + Now on CodePlex
279
JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
280
// ["Json.NET", "CodePlex"]
282
IList<string> categoriesText = categories.Select(c => (string)c).ToList();
288
public void LinqToJsonQuerying()
290
JObject rss = new JObject();
292
#region LinqToJsonQuerying
294
from p in rss["channel"]["item"].Children()
295
select (string)p["title"];
297
foreach (var item in postTitles)
299
Console.WriteLine(item);
303
//Json.NET 1.3 + New license + Now on CodePlex
306
from c in rss["channel"]["item"].Children()["category"].Values<string>()
308
orderby g.Count() descending
309
select new { Category = g.Key, Count = g.Count() };
311
foreach (var c in categories)
313
Console.WriteLine(c.Category + " - Count: " + c.Count);
316
//Json.NET - Count: 2
318
//CodePlex - Count: 1
322
#region LinqToJsonDeserializeObject
325
public string Original { get; set; }
326
public string Shortened { get; set; }
327
public string Short { get; set; }
328
public ShortieException Error { get; set; }
331
public class ShortieException
333
public int Code { get; set; }
334
public string ErrorMessage { get; set; }
338
public void LinqToJsonDeserializeExample()
340
#region LinqToJsonDeserializeExample
341
string jsonText = @"{
343
'original': 'http://www.foo.com/',
347
'msg':'No action taken'
351
JObject json = JObject.Parse(jsonText);
353
Shortie shortie = new Shortie
355
Original = (string)json["short"]["original"],
356
Short = (string)json["short"]["short"],
357
Error = new ShortieException
359
Code = (int)json["short"]["error"]["code"],
360
ErrorMessage = (string)json["short"]["error"]["msg"]
364
Console.WriteLine(shortie.Original);
365
// http://www.foo.com/
367
Console.WriteLine(shortie.Error.ErrorMessage);
372
public void SelectTokenSimple()
374
JObject o = new JObject();
376
#region SelectTokenSimple
377
string name = (string)o.SelectToken("Manufacturers[0].Name");
381
public void SelectTokenComplex()
383
#region SelectTokenComplex
384
JObject o = JObject.Parse(@"{
403
'Name': 'Elbow Grease',
407
'Name': 'Headlight Fluid',
415
string name = (string)o.SelectToken("Manufacturers[0].Name");
418
decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price");
421
string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name");
426
public void SelectTokenLinq()
428
JObject o = new JObject();
430
#region SelectTokenLinq
431
IList<string> storeNames = o.SelectToken("Stores").Select(s => (string)s).ToList();
435
IList<string> firstProductNames = o["Manufacturers"].Select(m => (string)m.SelectToken("Products[1].Name")).ToList();
439
decimal totalPrice = o["Manufacturers"].Sum(m => (decimal)m.SelectToken("Products[0].Price"));
b'\\ No newline at end of file'