PageRenderTime 244ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/mcs/class/System.Web.Extensions/Test/System.Web.Script.Serialization/JavaScriptSerializerTest.cs

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