JavaScriptSerializerTest.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323
  1. //
  2. // JavaScriptSerializer.cs
  3. //
  4. // Author:
  5. // Konstantin Triger <[email protected]>
  6. //
  7. // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Text;
  32. using NUnit.Framework;
  33. using System.Web.Script.Serialization;
  34. using System.Reflection;
  35. using System.Collections;
  36. using System.Drawing;
  37. using ComponentModel = System.ComponentModel;
  38. using System.Globalization;
  39. using System.Threading;
  40. using System.Text.RegularExpressions;
  41. using System.ComponentModel;
  42. using CategoryAttribute = NUnit.Framework.CategoryAttribute;
  43. using System.Web.UI.WebControls;
  44. using System.Collections.ObjectModel;
  45. namespace MonoTests.System.Web.Script.Serialization
  46. {
  47. [TestFixture]
  48. public class JavaScriptSerializerTest
  49. {
  50. enum MyEnum
  51. {
  52. AAA,
  53. BBB,
  54. CCC
  55. }
  56. #pragma warning disable 659
  57. class bug
  58. {
  59. //public DateTime dt;
  60. //public DateTime dt1;
  61. //public DateTime dt2;
  62. public bool bb;
  63. //Hashtable hash;
  64. public void Init() {
  65. //dt = DateTime.MaxValue;
  66. //dt1 = DateTime.MinValue;
  67. //dt2 = new DateTime ((DateTime.Now.Ticks / 10000) * 10000);
  68. bb = true;
  69. //hash = new Hashtable ();
  70. //hash.Add ("mykey", 1);
  71. }
  72. public override bool Equals (object obj) {
  73. if (!(obj is bug))
  74. return false;
  75. JavaScriptSerializerTest.FieldsEqual (this, obj);
  76. return true;
  77. }
  78. }
  79. class X
  80. {
  81. int x = 5;
  82. //int y;
  83. ulong _bb;
  84. Y[] _yy;
  85. Y [] _yyy = new Y [] { new Y (), new Y () };
  86. public int z;
  87. public char ch;
  88. public char ch_null;
  89. public string str;
  90. public byte b;
  91. public sbyte sb;
  92. public short sh;
  93. public ushort ush;
  94. public int i;
  95. public uint ui;
  96. public long l;
  97. public ulong ul;
  98. public float f;
  99. public float f1;
  100. public float f2;
  101. public float f3;
  102. public float f4;
  103. public double d;
  104. public double d1;
  105. public double d2;
  106. public double d3;
  107. public double d4;
  108. public decimal de;
  109. public decimal de1;
  110. public decimal de2;
  111. public decimal de3;
  112. public decimal de4;
  113. public Guid g;
  114. public Nullable<bool> nb;
  115. public DBNull dbn;
  116. IEnumerable<int> enum_int;
  117. IEnumerable enum_int1;
  118. public Uri uri;
  119. public Dictionary<string, Y> hash;
  120. public Point point;
  121. public void Init () {
  122. //y = 6;
  123. _bb = ulong.MaxValue - 5;
  124. _yy = new Y [] { new Y (), new Y () };
  125. z = 8;
  126. ch = (char) 0xFF56;
  127. ch_null = '\0';
  128. str = "\uFF56\uFF57\uF58FF59g";
  129. b = 253;
  130. sb = -48;
  131. sh = short.MinValue + 28;
  132. ush = ushort.MaxValue - 24;
  133. i = -234235453;
  134. ui = uint.MaxValue - 234234;
  135. l = long.MinValue + 28;
  136. ul = ulong.MaxValue - 3;
  137. f = float.NaN;
  138. f1 = float.NegativeInfinity;
  139. f2 = float.PositiveInfinity;
  140. f3 = float.MinValue;
  141. f4 = float.MaxValue;
  142. d = double.NaN;
  143. d1 = double.NegativeInfinity;
  144. d2 = double.PositiveInfinity;
  145. d3 = double.MinValue;
  146. d4 = double.MaxValue;
  147. de = decimal.MinusOne;
  148. de1 = decimal.Zero;
  149. de2 = decimal.One;
  150. de3 = decimal.MinValue;
  151. de4 = decimal.MaxValue;
  152. g = new Guid (234, 2, 354, new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 });
  153. nb = null;
  154. dbn = null;
  155. enum_int = new List<int> (MyEnum);
  156. enum_int1 = new ArrayList ();
  157. foreach (object obj in MyEnum1)
  158. ((ArrayList) enum_int1).Add (obj);
  159. uri = new Uri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  160. hash = new Dictionary<string, Y> ();
  161. Y y = new Y ();
  162. hash ["mykey"] = y;
  163. point = new Point (150, 150);
  164. }
  165. public IEnumerable<int> MyEnum {
  166. get {
  167. yield return 1;
  168. yield return 10;
  169. yield return 345;
  170. }
  171. set {
  172. enum_int = value;
  173. }
  174. }
  175. public IEnumerable MyEnum1 {
  176. get {
  177. yield return 1;
  178. yield return 10;
  179. yield return 345;
  180. }
  181. set {
  182. enum_int1 = value;
  183. }
  184. }
  185. public int AA {
  186. get { return x; }
  187. }
  188. public Y[] AA1 {
  189. get { return _yyy; }
  190. }
  191. public ulong BB {
  192. get { return _bb; }
  193. set { _bb = value; }
  194. }
  195. public Y[] YY {
  196. get { return _yy; }
  197. set { _yy = value; }
  198. }
  199. public override bool Equals (object obj) {
  200. if (!(obj is X))
  201. return false;
  202. JavaScriptSerializerTest.FieldsEqual (this, obj);
  203. return true;
  204. }
  205. }
  206. class Y
  207. {
  208. long _bb = 10;
  209. public long BB {
  210. get { return _bb; }
  211. set { _bb = value; }
  212. }
  213. public override bool Equals (object obj) {
  214. if (!(obj is Y))
  215. return false;
  216. JavaScriptSerializerTest.FieldsEqual(this, obj);
  217. return true;
  218. }
  219. }
  220. class YY
  221. {
  222. public YY ()
  223. {
  224. Y1 = new Y ();
  225. Y2 = new Y ();
  226. }
  227. public Y Y1;
  228. public Y Y2;
  229. }
  230. [TypeConverter (typeof (MyUriConverter))]
  231. class MyUri : Uri
  232. {
  233. public MyUri (string uriString, UriKind uriKind)
  234. : base (uriString, uriKind) {
  235. }
  236. public MyUri (Uri value)
  237. : base (value.AbsoluteUri) {
  238. }
  239. }
  240. class MyUriConverter : UriTypeConverter
  241. {
  242. public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  243. {
  244. return base.ConvertTo (context, culture, value, destinationType);
  245. }
  246. public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
  247. {
  248. Uri convertedUri = (Uri)base.ConvertFrom (context, culture, value);
  249. return new MyUri (convertedUri);
  250. }
  251. }
  252. [TypeConverter(typeof(MyPointConverter))]
  253. class MyPointContainer
  254. {
  255. public MyPointContainer ()
  256. {
  257. }
  258. public MyPointContainer (Point v)
  259. {
  260. p = v;
  261. }
  262. internal Point p;
  263. }
  264. class MyPointConverter : TypeConverter
  265. {
  266. public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
  267. {
  268. if (destinationType == typeof (string)) {
  269. return true;
  270. }
  271. return base.CanConvertTo (context, destinationType);
  272. }
  273. public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  274. {
  275. if (destinationType == typeof (string)) {
  276. MyPointContainer pc = (MyPointContainer) value;
  277. return pc.p.X + "," + pc.p.Y;
  278. }
  279. return base.ConvertTo (context, culture, value, destinationType);
  280. }
  281. public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
  282. {
  283. if (sourceType == typeof (string)) {
  284. return true;
  285. }
  286. return base.CanConvertFrom (context, sourceType);
  287. }
  288. public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
  289. {
  290. if (value is string) {
  291. string [] v = ((string) value).Split (new char [] { ',' });
  292. return new MyPointContainer(new Point (int.Parse (v [0]), int.Parse (v [1])));
  293. }
  294. return base.ConvertFrom (context, culture, value);
  295. }
  296. }
  297. #pragma warning restore 659
  298. [Test]
  299. [Category ("NotDotNet")]
  300. public void TestDefaults () {
  301. JavaScriptSerializer ser = new JavaScriptSerializer ();
  302. Assert.AreEqual (102400, ser.MaxJsonLength);
  303. Assert.AreEqual (100, ser.RecursionLimit);
  304. //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
  305. //l.Add (new MyJavaScriptConverter ());
  306. //ser.RegisterConverters (l);
  307. //string x = ser.Serialize (new X [] { new X (), new X () });
  308. //string s = ser.Serialize (new X());
  309. //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
  310. //X x = ser.Deserialize<X> (s);
  311. //object ddd = typeof (Y).GetMember ("BB");
  312. //object x1 = ser.Deserialize<X []> (null);
  313. //object x2 = ser.Deserialize<X []> ("");
  314. //object d = ser.Deserialize<X[]> (x);
  315. }
  316. [Test]
  317. public void TestDeserializeUnquotedKeys ()
  318. {
  319. JavaScriptSerializer ser = new JavaScriptSerializer ();
  320. IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:\"1\",itemTwo:\"2\"}");
  321. Assert.AreEqual ("1", dict ["itemOne"], "#A1");
  322. Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
  323. dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:1,itemTwo:2}");
  324. Assert.AreEqual (1, dict ["itemOne"], "#B1");
  325. Assert.AreEqual (2, dict ["itemTwo"], "#B2");
  326. }
  327. [Test]
  328. public void TestDeserializeUnquotedKeysWithSpaces ()
  329. {
  330. JavaScriptSerializer ser = new JavaScriptSerializer ();
  331. IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :\"1\",itemTwo:\"2\"}");
  332. Assert.AreEqual ("1", dict ["itemOne"], "#A1");
  333. Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
  334. dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :1, itemTwo :2}");
  335. Assert.AreEqual (1, dict ["itemOne"], "#B1");
  336. Assert.AreEqual (2, dict ["itemTwo"], "#B2");
  337. }
  338. [Test]
  339. public void TestDeserialize () {
  340. JavaScriptSerializer ser = new JavaScriptSerializer ();
  341. Assert.IsNull (ser.Deserialize<X> (""));
  342. X s = new X ();
  343. s.Init ();
  344. string x = ser.Serialize (s);
  345. Assert.AreEqual ("{\"z\":8,\"ch\":\"v\",\"ch_null\":null,\"str\":\"vwF59g\",\"b\":253,\"sb\":-48,\"sh\":-32740,\"ush\":65511,\"i\":-234235453,\"ui\":4294733061,\"l\":-9223372036854775780,\"ul\":18446744073709551612,\"f\":NaN,\"f1\":-Infinity,\"f2\":Infinity,\"f3\":-3.40282347E+38,\"f4\":3.40282347E+38,\"d\":NaN,\"d1\":-Infinity,\"d2\":Infinity,\"d3\":-1.7976931348623157E+308,\"d4\":1.7976931348623157E+308,\"de\":-1,\"de1\":0,\"de2\":1,\"de3\":-79228162514264337593543950335,\"de4\":79228162514264337593543950335,\"g\":\"000000ea-0002-0162-0102-030405060708\",\"nb\":null,\"dbn\":null,\"uri\":\"http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d\",\"hash\":{\"mykey\":{\"BB\":10}},\"point\":{\"IsEmpty\":false,\"X\":150,\"Y\":150},\"MyEnum\":[1,10,345],\"MyEnum1\":[1,10,345],\"AA\":5,\"AA1\":[{\"BB\":10},{\"BB\":10}],\"BB\":18446744073709551610,\"YY\":[{\"BB\":10},{\"BB\":10}]}", x, "#A1");
  346. X n = ser.Deserialize<X> (x);
  347. Assert.AreEqual (s, n, "#A2");
  348. //string json = "\\uFF56";
  349. //string result = ser.Deserialize<string> (json);
  350. //Assert.AreEqual ("\uFF56", result);
  351. //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
  352. }
  353. [Test]
  354. public void TestDeserializeTypeResolver ()
  355. {
  356. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  357. X x = new X ();
  358. x.Init ();
  359. string s = ser.Serialize (x);
  360. Console.WriteLine (s);
  361. Assert.AreEqual ("{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+X, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"z\":8,\"ch\":\"v\",\"ch_null\":null,\"str\":\"vwF59g\",\"b\":253,\"sb\":-48,\"sh\":-32740,\"ush\":65511,\"i\":-234235453,\"ui\":4294733061,\"l\":-9223372036854775780,\"ul\":18446744073709551612,\"f\":NaN,\"f1\":-Infinity,\"f2\":Infinity,\"f3\":-3.40282347E+38,\"f4\":3.40282347E+38,\"d\":NaN,\"d1\":-Infinity,\"d2\":Infinity,\"d3\":-1.7976931348623157E+308,\"d4\":1.7976931348623157E+308,\"de\":-1,\"de1\":0,\"de2\":1,\"de3\":-79228162514264337593543950335,\"de4\":79228162514264337593543950335,\"g\":\"000000ea-0002-0162-0102-030405060708\",\"nb\":null,\"dbn\":null,\"uri\":\"http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d\",\"hash\":{\"mykey\":{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}},\"point\":{\"__type\":\"System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\",\"IsEmpty\":false,\"X\":150,\"Y\":150},\"MyEnum\":[1,10,345],\"MyEnum1\":[1,10,345],\"AA\":5,\"AA1\":[{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10},{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}],\"BB\":18446744073709551610,\"YY\":[{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10},{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}]}", s, "#A1");
  362. X x2 = ser.Deserialize<X> (s);
  363. Assert.AreEqual (x, x2, "#A2");
  364. }
  365. [Test]
  366. public void TestDeserializeBugs () {
  367. JavaScriptSerializer ser = new JavaScriptSerializer ();
  368. bug s = new bug ();
  369. s.Init ();
  370. string x = ser.Serialize (s);
  371. bug n = ser.Deserialize<bug> (x);
  372. Assert.AreEqual (s, n);
  373. // Should check correctness with .Net GA:
  374. //js = ser.Serialize (Color.Red);
  375. //Color ccc = ser.Deserialize<Color> (js);
  376. //string xml = @"<root><node attr=""xxx""/></root>";
  377. //XmlDocument doc = new XmlDocument ();
  378. //doc.LoadXml (xml);
  379. //string js = ser.Serialize (doc);
  380. //DataTable table = new DataTable();
  381. //table.Columns.Add ("col1", typeof (int));
  382. //table.Columns.Add ("col2", typeof (float));
  383. //table.Rows.Add (1, 1f);
  384. //table.Rows.Add (234234, 2.4f);
  385. //string js = ser.Serialize (table);
  386. }
  387. static void FieldsEqual (object expected, object actual) {
  388. Assert.AreEqual (expected.GetType (), actual.GetType ());
  389. FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
  390. foreach (FieldInfo info in infos) {
  391. object value1 = info.GetValue (expected);
  392. object value2 = info.GetValue (actual);
  393. if (value1 is IEnumerable) {
  394. IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
  395. int index = -1;
  396. foreach (object x in (IEnumerable) value1) {
  397. if (!yenum.MoveNext ())
  398. Assert.Fail (info.Name + " index:" + index);
  399. index++;
  400. if (x is DictionaryEntry) {
  401. DictionaryEntry entry = (DictionaryEntry)x;
  402. IDictionary dict = (IDictionary) value2;
  403. Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
  404. }
  405. else
  406. Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
  407. }
  408. Assert.IsFalse (yenum.MoveNext (), info.Name);
  409. continue;
  410. }
  411. Assert.AreEqual (value1, value2, info.Name);
  412. }
  413. }
  414. [Test]
  415. [ExpectedException (typeof (ArgumentNullException))]
  416. public void TestDeserialize1 () {
  417. JavaScriptSerializer ser = new JavaScriptSerializer ();
  418. ser.Deserialize<string> (null);
  419. }
  420. [Test]
  421. [ExpectedException (typeof (ArgumentNullException))]
  422. public void TestDeserializeNullConverter () {
  423. JavaScriptSerializer ser = new JavaScriptSerializer ();
  424. ser.RegisterConverters (null);
  425. }
  426. [Test]
  427. public void TestDeserializeConverter () {
  428. JavaScriptSerializer ser = new JavaScriptSerializer ();
  429. List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
  430. list.Add (new MyJavaScriptConverter ());
  431. list.Add (new CultureInfoConverter ());
  432. ser.RegisterConverters (list);
  433. string result = ser.Serialize (new X [] { new X (), new X () });
  434. Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
  435. result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
  436. }
  437. [Test]
  438. public void TestDeserializeConverter1 () {
  439. JavaScriptSerializer serializer = new JavaScriptSerializer ();
  440. serializer.RegisterConverters (new JavaScriptConverter [] {new ListItemCollectionConverter()});
  441. ListBox ListBox1 = new ListBox ();
  442. ListBox1.Items.Add ("a1");
  443. ListBox1.Items.Add ("a2");
  444. ListBox1.Items.Add ("a3");
  445. string x = serializer.Serialize (ListBox1.Items);
  446. ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
  447. Assert.AreEqual (3, recoveredList.Count);
  448. }
  449. [Test]
  450. public void TestSerialize1 () {
  451. JavaScriptSerializer ser = new JavaScriptSerializer ();
  452. Assert.AreEqual("null", ser.Serialize(null));
  453. string js = ser.Serialize (1234);
  454. Assert.AreEqual ("1234", js);
  455. Assert.AreEqual (1234, ser.Deserialize<int> (js));
  456. js = ser.Serialize (1.1);
  457. Assert.AreEqual ("1.1", js);
  458. Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
  459. char [] chars = "faskjhfasd0981234".ToCharArray ();
  460. js = ser.Serialize (chars);
  461. char[] actual = ser.Deserialize<char[]> (js);
  462. Assert.AreEqual (chars.Length, actual.Length);
  463. for (int i = 0; i < chars.Length; i++)
  464. Assert.AreEqual (chars[i], actual[i]);
  465. string expected = @"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";
  466. string data = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
  467. string serRes = ser.Serialize (data);
  468. Assert.AreEqual (expected, serRes);
  469. string deserRes = ser.Deserialize<string> (serRes);
  470. Assert.AreEqual (data, deserRes);
  471. }
  472. [Test]
  473. [ExpectedException (typeof (ArgumentNullException))]
  474. [Category ("NotDotNet")]
  475. public void TestSerialize2 () {
  476. JavaScriptSerializer ser = new JavaScriptSerializer ();
  477. ser.Serialize ("aaa", (StringBuilder)null);
  478. }
  479. static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
  480. [Test]
  481. public void TestSerializeDate () {
  482. JavaScriptSerializer ser = new JavaScriptSerializer ();
  483. DateTime now = new DateTime (633213894056010000L);
  484. string actual = ser.Serialize (now);
  485. DateTime dateTime = now.ToUniversalTime ();
  486. long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
  487. object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
  488. Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
  489. Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
  490. }
  491. [Test]
  492. public void TestSerializeEnum () {
  493. JavaScriptSerializer ser = new JavaScriptSerializer ();
  494. string result = ser.Serialize (MyEnum.BBB);
  495. Assert.AreEqual ("1", result);
  496. Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
  497. }
  498. class MyJavaScriptConverter : JavaScriptConverter
  499. {
  500. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  501. throw new Exception ("The method or operation is not implemented.");
  502. }
  503. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  504. Array a = (Array) obj;
  505. Dictionary<string, object> d = new Dictionary<string, object> ();
  506. d.Add ("0", 1);
  507. d.Add ("1", 2);
  508. return d;
  509. //throw new Exception ("The method or operation is not implemented.");
  510. }
  511. public override IEnumerable<Type> SupportedTypes {
  512. get {
  513. yield return typeof (X[]);
  514. }
  515. }
  516. }
  517. sealed class CultureInfoConverter : JavaScriptConverter
  518. {
  519. static readonly Type typeofCultureInfo = typeof (CultureInfo);
  520. public override IEnumerable<Type> SupportedTypes {
  521. get { yield return typeofCultureInfo; }
  522. }
  523. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  524. throw new NotSupportedException ();
  525. }
  526. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  527. CultureInfo ci = (CultureInfo)obj;
  528. if (ci == null)
  529. return null;
  530. Dictionary<string, object> d = new Dictionary<string, object> ();
  531. d.Add ("name", ci.Name);
  532. d.Add ("numberFormat", ci.NumberFormat);
  533. d.Add ("dateTimeFormat", ci.DateTimeFormat);
  534. return d;
  535. }
  536. }
  537. public class ListItemCollectionConverter : JavaScriptConverter
  538. {
  539. public override IEnumerable<Type> SupportedTypes {
  540. //Define the ListItemCollection as a supported type.
  541. get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
  542. }
  543. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  544. ListItemCollection listType = obj as ListItemCollection;
  545. if (listType != null) {
  546. // Create the representation.
  547. Dictionary<string, object> result = new Dictionary<string, object> ();
  548. ArrayList itemsList = new ArrayList ();
  549. foreach (ListItem item in listType) {
  550. //Add each entry to the dictionary.
  551. Dictionary<string, object> listDict = new Dictionary<string, object> ();
  552. listDict.Add ("Value", item.Value);
  553. listDict.Add ("Text", item.Text);
  554. itemsList.Add (listDict);
  555. }
  556. result ["List"] = itemsList;
  557. return result;
  558. }
  559. return new Dictionary<string, object> ();
  560. }
  561. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  562. if (dictionary == null)
  563. throw new ArgumentNullException ("dictionary");
  564. if (type == typeof (ListItemCollection)) {
  565. // Create the instance to deserialize into.
  566. ListItemCollection list = new ListItemCollection ();
  567. // Deserialize the ListItemCollection's items.
  568. ArrayList itemsList = (ArrayList) dictionary ["List"];
  569. for (int i = 0; i < itemsList.Count; i++)
  570. list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
  571. return list;
  572. }
  573. return null;
  574. }
  575. }
  576. [Test]
  577. public void DeserializeObject () {
  578. object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
  579. Assert.IsNotNull (o as Dictionary<string, object>, "type");
  580. Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
  581. Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
  582. Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
  583. object [] array = (object []) dictionary ["Array"];
  584. Assert.AreEqual (true, (bool) array [0], "array [0]");
  585. Assert.AreEqual (false, (bool) array [1], "array [1]");
  586. Assert.AreEqual (0, (int) array [2], "array [2]");
  587. }
  588. [Test]
  589. public void DeserializeObject2 ()
  590. {
  591. JavaScriptSerializer ser = new JavaScriptSerializer ();
  592. Y y = new Y ();
  593. string s = ser.Serialize (y);
  594. object y2 = ser.DeserializeObject (s);
  595. Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
  596. }
  597. [Test]
  598. public void DeserializeObject3 ()
  599. {
  600. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
  601. Y y = new Y ();
  602. string s = ser.Serialize (y);
  603. object y2 = ser.DeserializeObject (s);
  604. Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
  605. }
  606. [Test]
  607. public void DeserializeObject4 ()
  608. {
  609. JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
  610. Y y = new Y ();
  611. string s = ser.Serialize (y);
  612. object y2 = ser.DeserializeObject (s);
  613. Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
  614. Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
  615. Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
  616. Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
  617. Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
  618. }
  619. [Test]
  620. [ExpectedException(typeof(ArgumentNullException))]
  621. public void SerializeWithResolverDeserializeWithout ()
  622. {
  623. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  624. Y y = new Y ();
  625. string s = ser.Serialize (y);
  626. ser = new JavaScriptSerializer ();
  627. object y2 = ser.DeserializeObject (s);
  628. }
  629. [Test]
  630. public void SerializeWithoutResolverDeserializeWith ()
  631. {
  632. JavaScriptSerializer ser = new JavaScriptSerializer ();
  633. Y y = new Y ();
  634. string s = ser.Serialize (y);
  635. ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  636. object y2 = ser.DeserializeObject (s);
  637. Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
  638. }
  639. class B
  640. {
  641. public int v1 = 15;
  642. public string s1 = "s1";
  643. }
  644. class D : B
  645. {
  646. public int v2 = 16;
  647. public string s2 = "s2";
  648. }
  649. class C
  650. {
  651. public B b1 = new B ();
  652. public B b2 = new D ();
  653. }
  654. [Test]
  655. public void SerializeDerivedType ()
  656. {
  657. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  658. B b = new D ();
  659. string s = ser.Serialize (b);
  660. B b2 = ser.Deserialize<B> (s);
  661. Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
  662. }
  663. [Test]
  664. public void SerializeDerivedType2 ()
  665. {
  666. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  667. B b = new D ();
  668. string s = ser.Serialize (b);
  669. B b2 = (B)ser.DeserializeObject (s);
  670. Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
  671. }
  672. [Test]
  673. public void SerializeContainedDerivedType ()
  674. {
  675. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  676. C c = new C ();
  677. string s = ser.Serialize (c);
  678. C c2 = ser.Deserialize<C> (s);
  679. Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
  680. Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
  681. }
  682. [Test]
  683. public void SerializeContainedDerivedType2 ()
  684. {
  685. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  686. C c = new C ();
  687. string s = ser.Serialize (c);
  688. C c2 = (C)ser.DeserializeObject (s);
  689. Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
  690. Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
  691. }
  692. [Test]
  693. public void SerializeWithTypeConverter ()
  694. {
  695. JavaScriptSerializer ser = new JavaScriptSerializer ();
  696. MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  697. string s = ser.Serialize (uri);
  698. MyUri uri2 = ser.Deserialize<MyUri> (s);
  699. Assert.AreEqual (uri, uri2);
  700. }
  701. [Test]
  702. public void SerializeWithTypeConverter2 ()
  703. {
  704. JavaScriptSerializer ser = new JavaScriptSerializer ();
  705. MyPointContainer pc = new MyPointContainer(new Point(15, 16));
  706. string s = ser.Serialize(pc);
  707. MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
  708. }
  709. [Test]
  710. public void MaxJsonLengthDeserializeObject ()
  711. {
  712. JavaScriptSerializer ser = new JavaScriptSerializer ();
  713. ser.MaxJsonLength = 16;
  714. object o = ser.DeserializeObject ("{s:'1234567890'}");
  715. }
  716. [Test]
  717. [ExpectedException(typeof(ArgumentException))]
  718. public void MaxJsonLengthDeserializeObjectToLong ()
  719. {
  720. JavaScriptSerializer ser = new JavaScriptSerializer ();
  721. ser.MaxJsonLength = 15;
  722. object o = ser.DeserializeObject ("{s:'1234567890'}");
  723. }
  724. [Test]
  725. public void MaxJsonLengthSerialize ()
  726. {
  727. JavaScriptSerializer ser = new JavaScriptSerializer ();
  728. ser.MaxJsonLength = 9;
  729. Y y = new Y ();
  730. string s = ser.Serialize (y);
  731. }
  732. [Test]
  733. [ExpectedException (typeof (InvalidOperationException))]
  734. public void MaxJsonLengthSerializeToLong ()
  735. {
  736. JavaScriptSerializer ser = new JavaScriptSerializer ();
  737. ser.MaxJsonLength = 8;
  738. Y y = new Y ();
  739. string s = ser.Serialize (y);
  740. }
  741. [Test]
  742. public void RecursionLimitDeserialize1 ()
  743. {
  744. JavaScriptSerializer ser = new JavaScriptSerializer ();
  745. ser.RecursionLimit = 3;
  746. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  747. }
  748. [Test]
  749. public void RecursionLimitDeserialize2 ()
  750. {
  751. JavaScriptSerializer ser = new JavaScriptSerializer ();
  752. ser.RecursionLimit = 2;
  753. YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
  754. }
  755. [Test]
  756. public void RecursionLimitDeserialize3 ()
  757. {
  758. JavaScriptSerializer ser = new JavaScriptSerializer ();
  759. ser.RecursionLimit = 1;
  760. object o = ser.DeserializeObject ("\"xxx\"");
  761. }
  762. [Test]
  763. [ExpectedException(typeof(ArgumentException))]
  764. public void RecursionLimitDeserializeToDeep ()
  765. {
  766. JavaScriptSerializer ser = new JavaScriptSerializer ();
  767. ser.RecursionLimit = 2;
  768. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  769. }
  770. [Test]
  771. public void RecursionLimitSerialize ()
  772. {
  773. JavaScriptSerializer ser = new JavaScriptSerializer ();
  774. ser.RecursionLimit = 3;
  775. YY yy = new YY();
  776. string s = ser.Serialize (yy);
  777. }
  778. [Test]
  779. [ExpectedException(typeof(ArgumentException))]
  780. public void RecursionLimitSerializeToDeep ()
  781. {
  782. JavaScriptSerializer ser = new JavaScriptSerializer ();
  783. ser.RecursionLimit = 2;
  784. YY yy = new YY ();
  785. string s = ser.Serialize (yy);
  786. }
  787. [Test]
  788. public void RecursionLimitSerialize2 ()
  789. {
  790. JavaScriptSerializer ser = new JavaScriptSerializer ();
  791. ser.RecursionLimit = 2;
  792. YY yy = new YY ();
  793. StringBuilder b = new StringBuilder ();
  794. bool caughtException = false;
  795. try {
  796. ser.Serialize (yy, b);
  797. }
  798. catch {
  799. caughtException = true;
  800. }
  801. Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
  802. Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
  803. }
  804. [Test]
  805. public void SimpleTypeResolver ()
  806. {
  807. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  808. YY yy = new YY ();
  809. string s = ser.Serialize (yy);
  810. string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
  811. Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
  812. expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
  813. Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
  814. }
  815. public class CustomResolver : JavaScriptTypeResolver
  816. {
  817. public CustomResolver ()
  818. {
  819. Reset ();
  820. }
  821. public override Type ResolveType (string id)
  822. {
  823. ResolvedIds.Add (id);
  824. switch (id) {
  825. case "YY":
  826. return typeof(YY);
  827. case "Y":
  828. return typeof (Y);
  829. case "X":
  830. return typeof (X);
  831. case "int":
  832. return typeof (int);
  833. case "long":
  834. return typeof (long);
  835. case "string":
  836. return typeof (string);
  837. case "point":
  838. return typeof(Point);
  839. }
  840. return null;
  841. }
  842. public override string ResolveTypeId (Type type)
  843. {
  844. if (type == null) {
  845. throw new ArgumentNullException ("type");
  846. }
  847. ResolvedTypes.Add (type.Name);
  848. if (type == typeof (YY))
  849. return "YY";
  850. if (type == typeof (Y))
  851. return "Y";
  852. if (type == typeof (X))
  853. return "X";
  854. if (type == typeof (int))
  855. return "int";
  856. if (type == typeof (long))
  857. return "long";
  858. if (type == typeof (string))
  859. return "string";
  860. if (type == typeof(Point))
  861. return "point";
  862. return null;
  863. }
  864. public static List<string> ResolvedTypes {
  865. get {
  866. if (resolvedTypes == null) {
  867. resolvedTypes = new List<string> ();
  868. }
  869. return resolvedTypes;
  870. }
  871. }
  872. public static List<string> ResolvedIds {
  873. get {
  874. if (resolvedIds == null) {
  875. resolvedIds = new List<string> ();
  876. }
  877. return resolvedIds;
  878. }
  879. }
  880. public static void Reset ()
  881. {
  882. resolvedIds = null;
  883. resolvedTypes = null;
  884. }
  885. private static List<string> resolvedTypes;
  886. private static List<string> resolvedIds;
  887. }
  888. [Test]
  889. [NUnit.Framework.Category ("NotWorking")]
  890. public void CustomTypeResolver ()
  891. {
  892. JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
  893. X x = new X ();
  894. x.Init ();
  895. string s = ser.Serialize (x);
  896. CustomResolver.Reset ();
  897. X x1 = (X) ser.DeserializeObject (s);
  898. Assert.IsTrue (x.Equals (x1), "x != x1");
  899. CustomResolver.Reset ();
  900. X x2 = ser.Deserialize<X> (s);
  901. Assert.IsTrue (x.Equals (x2), "x != x2");
  902. }
  903. [Test]
  904. public void InfinityAndNaN ()
  905. {
  906. JavaScriptSerializer ser = new JavaScriptSerializer ();
  907. double nan = Double.NaN;
  908. string s = ser.Serialize (nan);
  909. Assert.AreEqual (s, "NaN", "#A1");
  910. nan = (double)ser.DeserializeObject (s);
  911. Assert.AreEqual (Double.NaN, nan, "#A2");
  912. nan = (double)ser.Deserialize <double> (s);
  913. Assert.AreEqual (Double.NaN, nan, "#A3");
  914. double infinity = Double.PositiveInfinity;
  915. s = ser.Serialize (infinity);
  916. Assert.AreEqual (s, "Infinity", "#B1");
  917. infinity = (double)ser.DeserializeObject (s);
  918. Assert.AreEqual (Double.PositiveInfinity, infinity, "#B2");
  919. infinity = ser.Deserialize <double> (s);
  920. Assert.AreEqual (Double.PositiveInfinity, infinity, "#B3");
  921. infinity = Double.NegativeInfinity;
  922. s = ser.Serialize (infinity);
  923. Assert.AreEqual (s, "-Infinity", "#C1");
  924. infinity = (double)ser.DeserializeObject (s);
  925. Assert.AreEqual (Double.NegativeInfinity, infinity, "#C2");
  926. infinity = ser.Deserialize <double> (s);
  927. Assert.AreEqual (Double.NegativeInfinity, infinity, "#C3");
  928. var dict = new Dictionary <string, object> ();
  929. dict.Add ("A", Double.NaN);
  930. dict.Add ("B", Double.PositiveInfinity);
  931. dict.Add ("C", Double.NegativeInfinity);
  932. s = ser.Serialize (dict);
  933. Assert.AreEqual ("{\"A\":NaN,\"B\":Infinity,\"C\":-Infinity}", s, "#D1");
  934. dict = (Dictionary <string, object>)ser.DeserializeObject (s);
  935. Assert.AreEqual (Double.NaN, dict ["A"], "#D2");
  936. Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D3");
  937. Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D4");
  938. dict = (Dictionary <string, object>)ser.Deserialize <Dictionary <string, object>> (s);
  939. Assert.AreEqual (Double.NaN, dict ["A"], "#D5");
  940. Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D6");
  941. Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D7");
  942. var arr = new ArrayList () {
  943. Double.NaN,
  944. Double.PositiveInfinity,
  945. Double.NegativeInfinity};
  946. s = ser.Serialize (arr);
  947. Assert.AreEqual ("[NaN,Infinity,-Infinity]", s, "#E1");
  948. object[] arr2 = (object[])ser.DeserializeObject (s);
  949. Assert.AreEqual (3, arr2.Length, "#E2");
  950. Assert.AreEqual (Double.NaN, arr2 [0], "#E3");
  951. Assert.AreEqual (Double.PositiveInfinity, arr2 [1], "#E4");
  952. Assert.AreEqual (Double.NegativeInfinity, arr2 [2], "#E5");
  953. arr = ser.Deserialize <ArrayList> (s);
  954. Assert.AreEqual (3, arr.Count, "#E6");
  955. Assert.AreEqual (Double.NaN, arr [0], "#E7");
  956. Assert.AreEqual (Double.PositiveInfinity, arr [1], "#E8");
  957. Assert.AreEqual (Double.NegativeInfinity, arr [2], "#E9");
  958. }
  959. [Test]
  960. public void StandalonePrimitives ()
  961. {
  962. JavaScriptSerializer ser = new JavaScriptSerializer ();
  963. object o;
  964. int i;
  965. o = ser.DeserializeObject ("1");
  966. Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A1");
  967. i = (int)o;
  968. Assert.AreEqual (1, i, "#A2");
  969. o =ser.DeserializeObject ("-1");
  970. Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A3");
  971. i = (int)o;
  972. Assert.AreEqual (-1, i, "#A4");
  973. o = ser.DeserializeObject ("2147483649");
  974. Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B1");
  975. long l = (long)o;
  976. Assert.AreEqual (2147483649, l, "#B2");
  977. o = ser.DeserializeObject ("-2147483649");
  978. Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B3");
  979. l = (long)o;
  980. Assert.AreEqual (-2147483649, l, "#B4");
  981. o = ser.DeserializeObject ("9223372036854775808");
  982. Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C1");
  983. decimal d = (decimal)o;
  984. Assert.AreEqual (9223372036854775808m, d, "#C2");
  985. o = ser.DeserializeObject ("-9223372036854775809");
  986. Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C3");
  987. d = (decimal)o;
  988. Assert.AreEqual (-9223372036854775809m, d, "#C4");
  989. o = ser.DeserializeObject ("79228162514264337593543950336");
  990. Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D1");
  991. double db = (double)o;
  992. Assert.AreEqual (79228162514264337593543950336.0, db, "#D2");
  993. o = ser.DeserializeObject ("-79228162514264337593543950336");
  994. Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D3");
  995. db = (double)o;
  996. Assert.AreEqual (-79228162514264337593543950336.0, db, "#D4");
  997. o = ser.DeserializeObject ("\"test string\"");
  998. Assert.AreEqual (typeof (global::System.String), o.GetType (), "#E1");
  999. string s = (string)o;
  1000. Assert.AreEqual ("test string", s, "#E2");
  1001. o = ser.DeserializeObject ("true");
  1002. Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F1");
  1003. bool b = (bool)o;
  1004. Assert.AreEqual (true, b, "#F2");
  1005. o = ser.DeserializeObject ("false");
  1006. Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F3");
  1007. b = (bool)o;
  1008. Assert.AreEqual (false, b, "#F4");
  1009. o = ser.DeserializeObject ("-1.7976931348623157E+308");
  1010. Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G1");
  1011. db = (double)o;
  1012. Assert.AreEqual (Double.MinValue, db, "#G2");
  1013. o = ser.DeserializeObject ("1.7976931348623157E+308");
  1014. Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G3");
  1015. db = (double)o;
  1016. Assert.AreEqual (Double.MaxValue, db, "#G4");
  1017. }
  1018. class SomeDict : IDictionary<string, object>
  1019. {
  1020. void IDictionary<string, object>.Add (string key, object value) {
  1021. throw new NotSupportedException ();
  1022. }
  1023. bool IDictionary<string, object>.ContainsKey (string key) {
  1024. throw new NotSupportedException ();
  1025. }
  1026. ICollection<string> IDictionary<string, object>.Keys {
  1027. get { throw new NotSupportedException (); }
  1028. }
  1029. bool IDictionary<string, object>.Remove (string key) {
  1030. throw new NotSupportedException ();
  1031. }
  1032. bool IDictionary<string, object>.TryGetValue (string key, out object value) {
  1033. throw new NotSupportedException ();
  1034. }
  1035. ICollection<object> IDictionary<string, object>.Values {
  1036. get { throw new NotSupportedException (); }
  1037. }
  1038. object IDictionary<string, object>.this [string key] {
  1039. get { throw new NotSupportedException (); }
  1040. set { throw new NotSupportedException (); }
  1041. }
  1042. void ICollection<KeyValuePair<string, object>>.Add (KeyValuePair<string, object> item) {
  1043. throw new NotSupportedException ();
  1044. }
  1045. void ICollection<KeyValuePair<string, object>>.Clear () {
  1046. throw new NotSupportedException ();
  1047. }
  1048. bool ICollection<KeyValuePair<string, object>>.Contains (KeyValuePair<string, object> item) {
  1049. throw new NotSupportedException ();
  1050. }
  1051. void ICollection<KeyValuePair<string, object>>.CopyTo (KeyValuePair<string, object> [] array, int arrayIndex) {
  1052. throw new NotSupportedException ();
  1053. }
  1054. int ICollection<KeyValuePair<string, object>>.Count {
  1055. get { throw new NotSupportedException (); }
  1056. }
  1057. bool ICollection<KeyValuePair<string, object>>.IsReadOnly {
  1058. get { throw new NotSupportedException (); }
  1059. }
  1060. bool ICollection<KeyValuePair<string, object>>.Remove (KeyValuePair<string, object> item) {
  1061. throw new NotSupportedException ();
  1062. }
  1063. IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator () {
  1064. return GetEnumerator ();
  1065. }
  1066. IEnumerator IEnumerable.GetEnumerator () {
  1067. return ((IEnumerable<KeyValuePair<string, object>>) this).GetEnumerator ();
  1068. }
  1069. protected IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
  1070. yield return new KeyValuePair<string, object> ("hello", "world");
  1071. }
  1072. }
  1073. [Test] //bug #424704
  1074. public void NonGenericClassImplementingClosedGenericIDictionary ()
  1075. {
  1076. JavaScriptSerializer ser = new JavaScriptSerializer ();
  1077. SomeDict dictIn = new SomeDict ();
  1078. string s = ser.Serialize (dictIn);
  1079. Dictionary<string, object> dictOut = ser.Deserialize<Dictionary<string, object>> (s);
  1080. Assert.AreEqual (dictOut.Count, 1, "#1");
  1081. Assert.AreEqual (dictOut["hello"], "world", "#2");
  1082. }
  1083. [Test]
  1084. public void ConvertToIDictionary ()
  1085. {
  1086. JavaScriptSerializer jss = new JavaScriptSerializer ();
  1087. string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
  1088. object input = jss.Deserialize<IDictionary>(json);
  1089. IDictionary o = jss.ConvertToType<IDictionary>(input);
  1090. Assert.IsTrue (o != null, "#A1");
  1091. Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
  1092. }
  1093. [Test]
  1094. public void ConvertToGenericIDictionary ()
  1095. {
  1096. JavaScriptSerializer jss = new JavaScriptSerializer ();
  1097. string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
  1098. object input = jss.Deserialize<IDictionary>(json);
  1099. IDictionary <string, object> o = jss.ConvertToType<IDictionary <string, object>>(input);
  1100. Assert.IsTrue (o != null, "#A1");
  1101. Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
  1102. IDictionary <object, object> o1 = jss.ConvertToType<IDictionary <object, object>>(input);
  1103. Assert.IsTrue (o1 != null, "#B1");
  1104. Assert.AreEqual (typeof (Dictionary <object, object>), o1.GetType (), "#B2");
  1105. }
  1106. [Test]
  1107. [ExpectedException (typeof (InvalidOperationException))]
  1108. public void ConvertToGenericIDictionary_InvalidDefinition ()
  1109. {
  1110. JavaScriptSerializer jss = new JavaScriptSerializer ();
  1111. string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
  1112. object input = jss.Deserialize<IDictionary>(json);
  1113. IDictionary <int, object> o = jss.ConvertToType<IDictionary <int, object>>(input);
  1114. }
  1115. }
  1116. }