PageRenderTime 42ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Json45r7/Source/Src/Newtonsoft.Json.Tests/Linq/LinqToJsonTest.cs

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