JavaScriptSerializerTest.cs 37 KB

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