JavaScriptSerializerTest.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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. #if NET_3_5
  303. Assert.AreEqual (2097152, ser.MaxJsonLength);
  304. #else
  305. Assert.AreEqual (102400, ser.MaxJsonLength);
  306. #endif
  307. Assert.AreEqual (100, ser.RecursionLimit);
  308. //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
  309. //l.Add (new MyJavaScriptConverter ());
  310. //ser.RegisterConverters (l);
  311. //string x = ser.Serialize (new X [] { new X (), new X () });
  312. //string s = ser.Serialize (new X());
  313. //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
  314. //X x = ser.Deserialize<X> (s);
  315. //object ddd = typeof (Y).GetMember ("BB");
  316. //object x1 = ser.Deserialize<X []> (null);
  317. //object x2 = ser.Deserialize<X []> ("");
  318. //object d = ser.Deserialize<X[]> (x);
  319. }
  320. [Test]
  321. public void TestDeserializeUnquotedKeys ()
  322. {
  323. JavaScriptSerializer ser = new JavaScriptSerializer ();
  324. IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:\"1\",itemTwo:\"2\"}");
  325. Assert.AreEqual ("1", dict ["itemOne"], "#A1");
  326. Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
  327. dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:1,itemTwo:2}");
  328. Assert.AreEqual (1, dict ["itemOne"], "#B1");
  329. Assert.AreEqual (2, dict ["itemTwo"], "#B2");
  330. }
  331. [Test]
  332. public void TestDeserializeUnquotedKeysWithSpaces ()
  333. {
  334. JavaScriptSerializer ser = new JavaScriptSerializer ();
  335. IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :\"1\",itemTwo:\"2\"}");
  336. Assert.AreEqual ("1", dict ["itemOne"], "#A1");
  337. Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
  338. dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :1, itemTwo :2}");
  339. Assert.AreEqual (1, dict ["itemOne"], "#B1");
  340. Assert.AreEqual (2, dict ["itemTwo"], "#B2");
  341. }
  342. [Test]
  343. public void TestDeserialize () {
  344. JavaScriptSerializer ser = new JavaScriptSerializer ();
  345. Assert.IsNull (ser.Deserialize<X> (""));
  346. X s = new X ();
  347. s.Init ();
  348. string x = ser.Serialize (s);
  349. 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");
  350. X n = ser.Deserialize<X> (x);
  351. Assert.AreEqual (s, n, "#A2");
  352. //string json = "\\uFF56";
  353. //string result = ser.Deserialize<string> (json);
  354. //Assert.AreEqual ("\uFF56", result);
  355. //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
  356. }
  357. [Test]
  358. public void TestDeserializeTypeResolver ()
  359. {
  360. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  361. X x = new X ();
  362. x.Init ();
  363. string s = ser.Serialize (x);
  364. 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");
  365. X x2 = ser.Deserialize<X> (s);
  366. Assert.AreEqual (x, x2, "#A2");
  367. }
  368. [Test]
  369. public void TestDeserializeBugs () {
  370. JavaScriptSerializer ser = new JavaScriptSerializer ();
  371. bug s = new bug ();
  372. s.Init ();
  373. string x = ser.Serialize (s);
  374. bug n = ser.Deserialize<bug> (x);
  375. Assert.AreEqual (s, n);
  376. // Should check correctness with .Net GA:
  377. //js = ser.Serialize (Color.Red);
  378. //Color ccc = ser.Deserialize<Color> (js);
  379. //string xml = @"<root><node attr=""xxx""/></root>";
  380. //XmlDocument doc = new XmlDocument ();
  381. //doc.LoadXml (xml);
  382. //string js = ser.Serialize (doc);
  383. //DataTable table = new DataTable();
  384. //table.Columns.Add ("col1", typeof (int));
  385. //table.Columns.Add ("col2", typeof (float));
  386. //table.Rows.Add (1, 1f);
  387. //table.Rows.Add (234234, 2.4f);
  388. //string js = ser.Serialize (table);
  389. }
  390. static void FieldsEqual (object expected, object actual) {
  391. Assert.AreEqual (expected.GetType (), actual.GetType ());
  392. FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
  393. foreach (FieldInfo info in infos) {
  394. object value1 = info.GetValue (expected);
  395. object value2 = info.GetValue (actual);
  396. if (value1 is IEnumerable) {
  397. IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
  398. int index = -1;
  399. foreach (object x in (IEnumerable) value1) {
  400. if (!yenum.MoveNext ())
  401. Assert.Fail (info.Name + " index:" + index);
  402. index++;
  403. if (x is DictionaryEntry) {
  404. DictionaryEntry entry = (DictionaryEntry)x;
  405. IDictionary dict = (IDictionary) value2;
  406. Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
  407. }
  408. else
  409. Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
  410. }
  411. Assert.IsFalse (yenum.MoveNext (), info.Name);
  412. continue;
  413. }
  414. Assert.AreEqual (value1, value2, info.Name);
  415. }
  416. }
  417. [Test]
  418. [ExpectedException (typeof (ArgumentNullException))]
  419. public void TestDeserialize1 () {
  420. JavaScriptSerializer ser = new JavaScriptSerializer ();
  421. ser.Deserialize<string> (null);
  422. }
  423. [Test]
  424. [ExpectedException (typeof (ArgumentNullException))]
  425. public void TestDeserializeNullConverter () {
  426. JavaScriptSerializer ser = new JavaScriptSerializer ();
  427. ser.RegisterConverters (null);
  428. }
  429. [Test]
  430. public void TestDeserializeConverter () {
  431. JavaScriptSerializer ser = new JavaScriptSerializer ();
  432. List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
  433. list.Add (new MyJavaScriptConverter ());
  434. list.Add (new CultureInfoConverter ());
  435. ser.RegisterConverters (list);
  436. string result = ser.Serialize (new X [] { new X (), new X () });
  437. Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
  438. result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
  439. }
  440. [Test]
  441. public void TestDeserializeConverter1 () {
  442. JavaScriptSerializer serializer = new JavaScriptSerializer ();
  443. serializer.RegisterConverters (new JavaScriptConverter [] {new ListItemCollectionConverter()});
  444. ListBox ListBox1 = new ListBox ();
  445. ListBox1.Items.Add ("a1");
  446. ListBox1.Items.Add ("a2");
  447. ListBox1.Items.Add ("a3");
  448. string x = serializer.Serialize (ListBox1.Items);
  449. ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
  450. Assert.AreEqual (3, recoveredList.Count);
  451. }
  452. [Test]
  453. public void TestSerialize1 () {
  454. JavaScriptSerializer ser = new JavaScriptSerializer ();
  455. Assert.AreEqual("null", ser.Serialize(null));
  456. string js = ser.Serialize (1234);
  457. Assert.AreEqual ("1234", js);
  458. Assert.AreEqual (1234, ser.Deserialize<int> (js));
  459. js = ser.Serialize (1.1);
  460. Assert.AreEqual ("1.1", js);
  461. Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
  462. char [] chars = "faskjhfasd0981234".ToCharArray ();
  463. js = ser.Serialize (chars);
  464. char[] actual = ser.Deserialize<char[]> (js);
  465. Assert.AreEqual (chars.Length, actual.Length);
  466. for (int i = 0; i < chars.Length; i++)
  467. Assert.AreEqual (chars[i], actual[i]);
  468. 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{|}~""";
  469. 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{|}~";
  470. string serRes = ser.Serialize (data);
  471. Assert.AreEqual (expected, serRes);
  472. string deserRes = ser.Deserialize<string> (serRes);
  473. Assert.AreEqual (data, deserRes);
  474. }
  475. [Test]
  476. [ExpectedException (typeof (ArgumentNullException))]
  477. [Category ("NotDotNet")]
  478. public void TestSerialize2 () {
  479. JavaScriptSerializer ser = new JavaScriptSerializer ();
  480. ser.Serialize ("aaa", (StringBuilder)null);
  481. }
  482. static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
  483. [Test]
  484. public void TestSerializeDate () {
  485. JavaScriptSerializer ser = new JavaScriptSerializer ();
  486. DateTime now = new DateTime (633213894056010000L);
  487. string actual = ser.Serialize (now);
  488. DateTime dateTime = now.ToUniversalTime ();
  489. long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
  490. object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
  491. Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
  492. Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
  493. }
  494. [Test]
  495. public void TestSerializeEnum () {
  496. JavaScriptSerializer ser = new JavaScriptSerializer ();
  497. string result = ser.Serialize (MyEnum.BBB);
  498. Assert.AreEqual ("1", result);
  499. Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
  500. }
  501. class MyJavaScriptConverter : JavaScriptConverter
  502. {
  503. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  504. throw new Exception ("The method or operation is not implemented.");
  505. }
  506. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  507. Array a = (Array) obj;
  508. Dictionary<string, object> d = new Dictionary<string, object> ();
  509. d.Add ("0", 1);
  510. d.Add ("1", 2);
  511. return d;
  512. //throw new Exception ("The method or operation is not implemented.");
  513. }
  514. public override IEnumerable<Type> SupportedTypes {
  515. get {
  516. yield return typeof (X[]);
  517. }
  518. }
  519. }
  520. sealed class CultureInfoConverter : JavaScriptConverter
  521. {
  522. static readonly Type typeofCultureInfo = typeof (CultureInfo);
  523. public override IEnumerable<Type> SupportedTypes {
  524. get { yield return typeofCultureInfo; }
  525. }
  526. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  527. throw new NotSupportedException ();
  528. }
  529. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  530. CultureInfo ci = (CultureInfo)obj;
  531. if (ci == null)
  532. return null;
  533. Dictionary<string, object> d = new Dictionary<string, object> ();
  534. d.Add ("name", ci.Name);
  535. d.Add ("numberFormat", ci.NumberFormat);
  536. d.Add ("dateTimeFormat", ci.DateTimeFormat);
  537. return d;
  538. }
  539. }
  540. public class ListItemCollectionConverter : JavaScriptConverter
  541. {
  542. public override IEnumerable<Type> SupportedTypes {
  543. //Define the ListItemCollection as a supported type.
  544. get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
  545. }
  546. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  547. ListItemCollection listType = obj as ListItemCollection;
  548. if (listType != null) {
  549. // Create the representation.
  550. Dictionary<string, object> result = new Dictionary<string, object> ();
  551. ArrayList itemsList = new ArrayList ();
  552. foreach (ListItem item in listType) {
  553. //Add each entry to the dictionary.
  554. Dictionary<string, object> listDict = new Dictionary<string, object> ();
  555. listDict.Add ("Value", item.Value);
  556. listDict.Add ("Text", item.Text);
  557. itemsList.Add (listDict);
  558. }
  559. result ["List"] = itemsList;
  560. return result;
  561. }
  562. return new Dictionary<string, object> ();
  563. }
  564. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  565. if (dictionary == null)
  566. throw new ArgumentNullException ("dictionary");
  567. if (type == typeof (ListItemCollection)) {
  568. // Create the instance to deserialize into.
  569. ListItemCollection list = new ListItemCollection ();
  570. // Deserialize the ListItemCollection's items.
  571. ArrayList itemsList = (ArrayList) dictionary ["List"];
  572. for (int i = 0; i < itemsList.Count; i++)
  573. list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
  574. return list;
  575. }
  576. return null;
  577. }
  578. }
  579. [Test]
  580. public void DeserializeObject () {
  581. object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
  582. Assert.IsNotNull (o as Dictionary<string, object>, "type");
  583. Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
  584. Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
  585. Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
  586. object [] array = (object []) dictionary ["Array"];
  587. Assert.AreEqual (true, (bool) array [0], "array [0]");
  588. Assert.AreEqual (false, (bool) array [1], "array [1]");
  589. Assert.AreEqual (0, (int) array [2], "array [2]");
  590. }
  591. [Test]
  592. public void DeserializeObject2 ()
  593. {
  594. JavaScriptSerializer ser = new JavaScriptSerializer ();
  595. Y y = new Y ();
  596. string s = ser.Serialize (y);
  597. object y2 = ser.DeserializeObject (s);
  598. Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
  599. }
  600. [Test]
  601. public void DeserializeObject3 ()
  602. {
  603. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
  604. Y y = new Y ();
  605. string s = ser.Serialize (y);
  606. object y2 = ser.DeserializeObject (s);
  607. Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
  608. }
  609. [Test]
  610. public void DeserializeObject4 ()
  611. {
  612. JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
  613. Y y = new Y ();
  614. string s = ser.Serialize (y);
  615. object y2 = ser.DeserializeObject (s);
  616. Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
  617. Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
  618. Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
  619. Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
  620. Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
  621. }
  622. [Test]
  623. [ExpectedException(typeof(ArgumentNullException))]
  624. public void SerializeWithResolverDeserializeWithout ()
  625. {
  626. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  627. Y y = new Y ();
  628. string s = ser.Serialize (y);
  629. ser = new JavaScriptSerializer ();
  630. object y2 = ser.DeserializeObject (s);
  631. }
  632. [Test]
  633. public void SerializeWithoutResolverDeserializeWith ()
  634. {
  635. JavaScriptSerializer ser = new JavaScriptSerializer ();
  636. Y y = new Y ();
  637. string s = ser.Serialize (y);
  638. ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  639. object y2 = ser.DeserializeObject (s);
  640. Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
  641. }
  642. class B
  643. {
  644. public int v1 = 15;
  645. public string s1 = "s1";
  646. }
  647. class D : B
  648. {
  649. public int v2 = 16;
  650. public string s2 = "s2";
  651. }
  652. class C
  653. {
  654. public B b1 = new B ();
  655. public B b2 = new D ();
  656. }
  657. [Test]
  658. public void SerializeDerivedType ()
  659. {
  660. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  661. B b = new D ();
  662. string s = ser.Serialize (b);
  663. B b2 = ser.Deserialize<B> (s);
  664. Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
  665. }
  666. [Test]
  667. public void SerializeDerivedType2 ()
  668. {
  669. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  670. B b = new D ();
  671. string s = ser.Serialize (b);
  672. B b2 = (B)ser.DeserializeObject (s);
  673. Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
  674. }
  675. [Test]
  676. public void SerializeContainedDerivedType ()
  677. {
  678. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  679. C c = new C ();
  680. string s = ser.Serialize (c);
  681. C c2 = ser.Deserialize<C> (s);
  682. Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
  683. Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
  684. }
  685. [Test]
  686. public void SerializeContainedDerivedType2 ()
  687. {
  688. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  689. C c = new C ();
  690. string s = ser.Serialize (c);
  691. C c2 = (C)ser.DeserializeObject (s);
  692. Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
  693. Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
  694. }
  695. [Test]
  696. public void SerializeWithTypeConverter ()
  697. {
  698. JavaScriptSerializer ser = new JavaScriptSerializer ();
  699. MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  700. string s = ser.Serialize (uri);
  701. MyUri uri2 = ser.Deserialize<MyUri> (s);
  702. Assert.AreEqual (uri, uri2);
  703. }
  704. [Test]
  705. public void SerializeWithTypeConverter2 ()
  706. {
  707. JavaScriptSerializer ser = new JavaScriptSerializer ();
  708. MyPointContainer pc = new MyPointContainer(new Point(15, 16));
  709. string s = ser.Serialize(pc);
  710. MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
  711. }
  712. [Test]
  713. public void MaxJsonLengthDeserializeObject ()
  714. {
  715. JavaScriptSerializer ser = new JavaScriptSerializer ();
  716. ser.MaxJsonLength = 16;
  717. object o = ser.DeserializeObject ("{s:'1234567890'}");
  718. }
  719. [Test]
  720. [ExpectedException(typeof(ArgumentException))]
  721. public void MaxJsonLengthDeserializeObjectToLong ()
  722. {
  723. JavaScriptSerializer ser = new JavaScriptSerializer ();
  724. ser.MaxJsonLength = 15;
  725. object o = ser.DeserializeObject ("{s:'1234567890'}");
  726. }
  727. [Test]
  728. public void MaxJsonLengthSerialize ()
  729. {
  730. JavaScriptSerializer ser = new JavaScriptSerializer ();
  731. ser.MaxJsonLength = 9;
  732. Y y = new Y ();
  733. string s = ser.Serialize (y);
  734. }
  735. [Test]
  736. [ExpectedException (typeof (InvalidOperationException))]
  737. public void MaxJsonLengthSerializeToLong ()
  738. {
  739. JavaScriptSerializer ser = new JavaScriptSerializer ();
  740. ser.MaxJsonLength = 8;
  741. Y y = new Y ();
  742. string s = ser.Serialize (y);
  743. }
  744. [Test]
  745. public void RecursionLimitDeserialize1 ()
  746. {
  747. JavaScriptSerializer ser = new JavaScriptSerializer ();
  748. ser.RecursionLimit = 3;
  749. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  750. }
  751. [Test]
  752. public void RecursionLimitDeserialize2 ()
  753. {
  754. JavaScriptSerializer ser = new JavaScriptSerializer ();
  755. ser.RecursionLimit = 2;
  756. YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
  757. }
  758. [Test]
  759. public void RecursionLimitDeserialize3 ()
  760. {
  761. JavaScriptSerializer ser = new JavaScriptSerializer ();
  762. ser.RecursionLimit = 1;
  763. object o = ser.DeserializeObject ("\"xxx\"");
  764. }
  765. [Test]
  766. [ExpectedException(typeof(ArgumentException))]
  767. public void RecursionLimitDeserializeToDeep ()
  768. {
  769. JavaScriptSerializer ser = new JavaScriptSerializer ();
  770. ser.RecursionLimit = 2;
  771. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  772. }
  773. [Test]
  774. public void RecursionLimitSerialize ()
  775. {
  776. JavaScriptSerializer ser = new JavaScriptSerializer ();
  777. ser.RecursionLimit = 3;
  778. YY yy = new YY();
  779. string s = ser.Serialize (yy);
  780. }
  781. [Test]
  782. [ExpectedException(typeof(ArgumentException))]
  783. public void RecursionLimitSerializeToDeep ()
  784. {
  785. JavaScriptSerializer ser = new JavaScriptSerializer ();
  786. ser.RecursionLimit = 2;
  787. YY yy = new YY ();
  788. string s = ser.Serialize (yy);
  789. }
  790. [Test]
  791. public void RecursionLimitSerialize2 ()
  792. {
  793. JavaScriptSerializer ser = new JavaScriptSerializer ();
  794. ser.RecursionLimit = 2;
  795. YY yy = new YY ();
  796. StringBuilder b = new StringBuilder ();
  797. bool caughtException = false;
  798. try {
  799. ser.Serialize (yy, b);
  800. }
  801. catch {
  802. caughtException = true;
  803. }
  804. Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
  805. Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
  806. }
  807. [Test]
  808. public void SimpleTypeResolver ()
  809. {
  810. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  811. YY yy = new YY ();
  812. string s = ser.Serialize (yy);
  813. string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
  814. Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
  815. expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
  816. Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
  817. }
  818. public class CustomResolver : JavaScriptTypeResolver
  819. {
  820. public CustomResolver ()
  821. {
  822. Reset ();
  823. }
  824. public override Type ResolveType (string id)
  825. {
  826. ResolvedIds.Add (id);
  827. switch (id) {
  828. case "YY":
  829. return typeof(YY);
  830. case "Y":
  831. return typeof (Y);
  832. case "X":
  833. return typeof (X);
  834. case "int":
  835. return typeof (int);
  836. case "long":
  837. return typeof (long);
  838. case "string":
  839. return typeof (string);
  840. case "point":
  841. return typeof(Point);
  842. }
  843. return null;
  844. }
  845. public override string ResolveTypeId (Type type)
  846. {
  847. if (type == null) {
  848. throw new ArgumentNullException ("type");
  849. }
  850. ResolvedTypes.Add (type.Name);
  851. if (type == typeof (YY))
  852. return "YY";
  853. if (type == typeof (Y))
  854. return "Y";
  855. if (type == typeof (X))
  856. return "X";
  857. if (type == typeof (int))
  858. return "int";
  859. if (type == typeof (long))
  860. return "long";
  861. if (type == typeof (string))
  862. return "string";
  863. if (type == typeof(Point))
  864. return "point";
  865. return null;
  866. }
  867. public static List<string> ResolvedTypes {
  868. get {
  869. if (resolvedTypes == null) {
  870. resolvedTypes = new List<string> ();
  871. }
  872. return resolvedTypes;
  873. }
  874. }
  875. public static List<string> ResolvedIds {
  876. get {
  877. if (resolvedIds == null) {
  878. resolvedIds = new List<string> ();
  879. }
  880. return resolvedIds;
  881. }
  882. }
  883. public static void Reset ()
  884. {
  885. resolvedIds = null;
  886. resolvedTypes = null;
  887. }
  888. private static List<string> resolvedTypes;
  889. private static List<string> resolvedIds;
  890. }
  891. [Test]
  892. [NUnit.Framework.Category ("NotWorking")]
  893. public void CustomTypeResolver ()
  894. {
  895. JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
  896. X x = new X ();
  897. x.Init ();
  898. string s = ser.Serialize (x);
  899. CustomResolver.Reset ();
  900. X x1 = (X) ser.DeserializeObject (s);
  901. Assert.IsTrue (x.Equals (x1), "x != x1");
  902. CustomResolver.Reset ();
  903. X x2 = ser.Deserialize<X> (s);
  904. Assert.IsTrue (x.Equals (x2), "x != x2");
  905. }
  906. [Test]
  907. public void InfinityAndNaN ()
  908. {
  909. JavaScriptSerializer ser = new JavaScriptSerializer ();
  910. double nan = Double.NaN;
  911. string s = ser.Serialize (nan);
  912. Assert.AreEqual (s, "NaN", "#A1");
  913. nan = (double)ser.DeserializeObject (s);
  914. Assert.AreEqual (Double.NaN, nan, "#A2");
  915. nan = (double)ser.Deserialize <double> (s);
  916. Assert.AreEqual (Double.NaN, nan, "#A3");
  917. double infinity = Double.PositiveInfinity;
  918. s = ser.Serialize (infinity);
  919. Assert.AreEqual (s, "Infinity", "#B1");
  920. infinity = (double)ser.DeserializeObject (s);
  921. Assert.AreEqual (Double.PositiveInfinity, infinity, "#B2");
  922. infinity = ser.Deserialize <double> (s);
  923. Assert.AreEqual (Double.PositiveInfinity, infinity, "#B3");
  924. infinity = Double.NegativeInfinity;
  925. s = ser.Serialize (infinity);
  926. Assert.AreEqual (s, "-Infinity", "#C1");
  927. infinity = (double)ser.DeserializeObject (s);
  928. Assert.AreEqual (Double.NegativeInfinity, infinity, "#C2");
  929. infinity = ser.Deserialize <double> (s);
  930. Assert.AreEqual (Double.NegativeInfinity, infinity, "#C3");
  931. var dict = new Dictionary <string, object> ();
  932. dict.Add ("A", Double.NaN);
  933. dict.Add ("B", Double.PositiveInfinity);
  934. dict.Add ("C", Double.NegativeInfinity);
  935. s = ser.Serialize (dict);
  936. Assert.AreEqual ("{\"A\":NaN,\"B\":Infinity,\"C\":-Infinity}", s, "#D1");
  937. dict = (Dictionary <string, object>)ser.DeserializeObject (s);
  938. Assert.AreEqual (Double.NaN, dict ["A"], "#D2");
  939. Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D3");
  940. Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D4");
  941. dict = (Dictionary <string, object>)ser.Deserialize <Dictionary <string, object>> (s);
  942. Assert.AreEqual (Double.NaN, dict ["A"], "#D5");
  943. Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D6");
  944. Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D7");
  945. var arr = new ArrayList () {
  946. Double.NaN,
  947. Double.PositiveInfinity,
  948. Double.NegativeInfinity};
  949. s = ser.Serialize (arr);
  950. Assert.AreEqual ("[NaN,Infinity,-Infinity]", s, "#E1");
  951. object[] arr2 = (object[])ser.DeserializeObject (s);
  952. Assert.AreEqual (3, arr2.Length, "#E2");
  953. Assert.AreEqual (Double.NaN, arr2 [0], "#E3");
  954. Assert.AreEqual (Double.PositiveInfinity, arr2 [1], "#E4");
  955. Assert.AreEqual (Double.NegativeInfinity, arr2 [2], "#E5");
  956. arr = ser.Deserialize <ArrayList> (s);
  957. Assert.AreEqual (3, arr.Count, "#E6");
  958. Assert.AreEqual (Double.NaN, arr [0], "#E7");
  959. Assert.AreEqual (Double.PositiveInfinity, arr [1], "#E8");
  960. Assert.AreEqual (Double.NegativeInfinity, arr [2], "#E9");
  961. }
  962. [Test]
  963. public void StandalonePrimitives ()
  964. {
  965. JavaScriptSerializer ser = new JavaScriptSerializer ();
  966. object o;
  967. int i;
  968. o = ser.DeserializeObject ("1");
  969. Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A1");
  970. i = (int)o;
  971. Assert.AreEqual (1, i, "#A2");
  972. o =ser.DeserializeObject ("-1");
  973. Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A3");
  974. i = (int)o;
  975. Assert.AreEqual (-1, i, "#A4");
  976. o = ser.DeserializeObject ("2147483649");
  977. Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B1");
  978. long l = (long)o;
  979. Assert.AreEqual (2147483649, l, "#B2");
  980. o = ser.DeserializeObject ("-2147483649");
  981. Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B3");
  982. l = (long)o;
  983. Assert.AreEqual (-2147483649, l, "#B4");
  984. o = ser.DeserializeObject ("9223372036854775808");
  985. Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C1");
  986. decimal d = (decimal)o;
  987. Assert.AreEqual (9223372036854775808m, d, "#C2");
  988. o = ser.DeserializeObject ("-9223372036854775809");
  989. Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C3");
  990. d = (decimal)o;
  991. Assert.AreEqual (-9223372036854775809m, d, "#C4");
  992. o = ser.DeserializeObject ("79228162514264337593543950336");
  993. Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D1");
  994. double db = (double)o;
  995. Assert.AreEqual (79228162514264337593543950336.0, db, "#D2");
  996. o = ser.DeserializeObject ("-79228162514264337593543950336");
  997. Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D3");
  998. db = (double)o;
  999. Assert.AreEqual (-79228162514264337593543950336.0, db, "#D4");
  1000. o = ser.DeserializeObject ("\"test string\"");
  1001. Assert.AreEqual (typeof (global::System.String), o.GetType (), "#E1");
  1002. string s = (string)o;
  1003. Assert.AreEqual ("test string", s, "#E2");
  1004. o = ser.DeserializeObject ("true");
  1005. Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F1");
  1006. bool b = (bool)o;
  1007. Assert.AreEqual (true, b, "#F2");
  1008. o = ser.DeserializeObject ("false");
  1009. Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F3");
  1010. b = (bool)o;
  1011. Assert.AreEqual (false, b, "#F4");
  1012. o = ser.DeserializeObject ("-1.7976931348623157E+308");
  1013. Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G1");
  1014. db = (double)o;
  1015. Assert.AreEqual (Double.MinValue, db, "#G2");
  1016. o = ser.DeserializeObject ("1.7976931348623157E+308");
  1017. Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G3");
  1018. db = (double)o;
  1019. Assert.AreEqual (Double.MaxValue, db, "#G4");
  1020. }
  1021. class SomeDict : IDictionary<string, object>
  1022. {
  1023. void IDictionary<string, object>.Add (string key, object value) {
  1024. throw new NotSupportedException ();
  1025. }
  1026. bool IDictionary<string, object>.ContainsKey (string key) {
  1027. throw new NotSupportedException ();
  1028. }
  1029. ICollection<string> IDictionary<string, object>.Keys {
  1030. get { throw new NotSupportedException (); }
  1031. }
  1032. bool IDictionary<string, object>.Remove (string key) {
  1033. throw new NotSupportedException ();
  1034. }
  1035. bool IDictionary<string, object>.TryGetValue (string key, out object value) {
  1036. throw new NotSupportedException ();
  1037. }
  1038. ICollection<object> IDictionary<string, object>.Values {
  1039. get { throw new NotSupportedException (); }
  1040. }
  1041. object IDictionary<string, object>.this [string key] {
  1042. get { throw new NotSupportedException (); }
  1043. set { throw new NotSupportedException (); }
  1044. }
  1045. void ICollection<KeyValuePair<string, object>>.Add (KeyValuePair<string, object> item) {
  1046. throw new NotSupportedException ();
  1047. }
  1048. void ICollection<KeyValuePair<string, object>>.Clear () {
  1049. throw new NotSupportedException ();
  1050. }
  1051. bool ICollection<KeyValuePair<string, object>>.Contains (KeyValuePair<string, object> item) {
  1052. throw new NotSupportedException ();
  1053. }
  1054. void ICollection<KeyValuePair<string, object>>.CopyTo (KeyValuePair<string, object> [] array, int arrayIndex) {
  1055. throw new NotSupportedException ();
  1056. }
  1057. int ICollection<KeyValuePair<string, object>>.Count {
  1058. get { throw new NotSupportedException (); }
  1059. }
  1060. bool ICollection<KeyValuePair<string, object>>.IsReadOnly {
  1061. get { throw new NotSupportedException (); }
  1062. }
  1063. bool ICollection<KeyValuePair<string, object>>.Remove (KeyValuePair<string, object> item) {
  1064. throw new NotSupportedException ();
  1065. }
  1066. IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator () {
  1067. return GetEnumerator ();
  1068. }
  1069. IEnumerator IEnumerable.GetEnumerator () {
  1070. return ((IEnumerable<KeyValuePair<string, object>>) this).GetEnumerator ();
  1071. }
  1072. protected IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
  1073. yield return new KeyValuePair<string, object> ("hello", "world");
  1074. }
  1075. }
  1076. [Test] //bug #424704
  1077. public void NonGenericClassImplementingClosedGenericIDictionary ()
  1078. {
  1079. JavaScriptSerializer ser = new JavaScriptSerializer ();
  1080. SomeDict dictIn = new SomeDict ();
  1081. string s = ser.Serialize (dictIn);
  1082. Dictionary<string, object> dictOut = ser.Deserialize<Dictionary<string, object>> (s);
  1083. Assert.AreEqual (dictOut.Count, 1, "#1");
  1084. Assert.AreEqual (dictOut["hello"], "world", "#2");
  1085. }
  1086. [Test]
  1087. public void ConvertToIDictionary ()
  1088. {
  1089. JavaScriptSerializer jss = new JavaScriptSerializer ();
  1090. 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}}";
  1091. object input = jss.Deserialize<IDictionary>(json);
  1092. IDictionary o = jss.ConvertToType<IDictionary>(input);
  1093. Assert.IsTrue (o != null, "#A1");
  1094. Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
  1095. }
  1096. [Test]
  1097. public void ConvertToGenericIDictionary ()
  1098. {
  1099. JavaScriptSerializer jss = new JavaScriptSerializer ();
  1100. 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}}";
  1101. object input = jss.Deserialize<IDictionary>(json);
  1102. IDictionary <string, object> o = jss.ConvertToType<IDictionary <string, object>>(input);
  1103. Assert.IsTrue (o != null, "#A1");
  1104. Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
  1105. IDictionary <object, object> o1 = jss.ConvertToType<IDictionary <object, object>>(input);
  1106. Assert.IsTrue (o1 != null, "#B1");
  1107. Assert.AreEqual (typeof (Dictionary <object, object>), o1.GetType (), "#B2");
  1108. }
  1109. [Test]
  1110. [ExpectedException (typeof (InvalidOperationException))]
  1111. public void ConvertToGenericIDictionary_InvalidDefinition ()
  1112. {
  1113. JavaScriptSerializer jss = new JavaScriptSerializer ();
  1114. 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}}";
  1115. object input = jss.Deserialize<IDictionary>(json);
  1116. IDictionary <int, object> o = jss.ConvertToType<IDictionary <int, object>>(input);
  1117. }
  1118. }
  1119. }