JavaScriptSerializerTest.cs 50 KB

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