JavaScriptSerializerTest.cs 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028
  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 TestDeserialize () {
  318. JavaScriptSerializer ser = new JavaScriptSerializer ();
  319. Assert.IsNull (ser.Deserialize<X> (""));
  320. X s = new X ();
  321. s.Init ();
  322. string x = ser.Serialize (s);
  323. X n = ser.Deserialize<X> (x);
  324. Assert.AreEqual (s, n);
  325. //string json = "\\uFF56";
  326. //string result = ser.Deserialize<string> (json);
  327. //Assert.AreEqual ("\uFF56", result);
  328. //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
  329. }
  330. [Test]
  331. public void TestDeserializeTypeResolver ()
  332. {
  333. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  334. X x = new X ();
  335. x.Init ();
  336. string s = ser.Serialize (x);
  337. X x2 = ser.Deserialize<X> (s);
  338. Assert.AreEqual (x, x2);
  339. }
  340. [Test]
  341. [Category("NotWorking")]
  342. public void TestDeserializeBugs () {
  343. JavaScriptSerializer ser = new JavaScriptSerializer ();
  344. bug s = new bug ();
  345. s.Init ();
  346. string x = ser.Serialize (s);
  347. bug n = ser.Deserialize<bug> (x);
  348. Assert.AreEqual (s, n);
  349. // Should check correctness with .Net GA:
  350. //js = ser.Serialize (Color.Red);
  351. //Color ccc = ser.Deserialize<Color> (js);
  352. //string xml = @"<root><node attr=""xxx""/></root>";
  353. //XmlDocument doc = new XmlDocument ();
  354. //doc.LoadXml (xml);
  355. //string js = ser.Serialize (doc);
  356. //DataTable table = new DataTable();
  357. //table.Columns.Add ("col1", typeof (int));
  358. //table.Columns.Add ("col2", typeof (float));
  359. //table.Rows.Add (1, 1f);
  360. //table.Rows.Add (234234, 2.4f);
  361. //string js = ser.Serialize (table);
  362. }
  363. static void FieldsEqual (object expected, object actual) {
  364. Assert.AreEqual (expected.GetType (), actual.GetType ());
  365. FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
  366. foreach (FieldInfo info in infos) {
  367. object value1 = info.GetValue (expected);
  368. object value2 = info.GetValue (actual);
  369. if (value1 is IEnumerable) {
  370. IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
  371. int index = -1;
  372. foreach (object x in (IEnumerable) value1) {
  373. if (!yenum.MoveNext ())
  374. Assert.Fail (info.Name + " index:" + index);
  375. index++;
  376. if (x is DictionaryEntry) {
  377. DictionaryEntry entry = (DictionaryEntry)x;
  378. IDictionary dict = (IDictionary) value2;
  379. Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
  380. }
  381. else
  382. Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
  383. }
  384. Assert.IsFalse (yenum.MoveNext (), info.Name);
  385. continue;
  386. }
  387. Assert.AreEqual (value1, value2, info.Name);
  388. }
  389. }
  390. [Test]
  391. [ExpectedException (typeof (ArgumentNullException))]
  392. public void TestDeserialize1 () {
  393. JavaScriptSerializer ser = new JavaScriptSerializer ();
  394. ser.Deserialize<string> (null);
  395. }
  396. [Test]
  397. [ExpectedException (typeof (ArgumentNullException))]
  398. public void TestDeserializeNullConverter () {
  399. JavaScriptSerializer ser = new JavaScriptSerializer ();
  400. ser.RegisterConverters (null);
  401. }
  402. [Test]
  403. public void TestDeserializeConverter () {
  404. JavaScriptSerializer ser = new JavaScriptSerializer ();
  405. List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
  406. list.Add (new MyJavaScriptConverter ());
  407. list.Add (new CultureInfoConverter ());
  408. ser.RegisterConverters (list);
  409. string result = ser.Serialize (new X [] { new X (), new X () });
  410. Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
  411. result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
  412. }
  413. [Test]
  414. public void TestDeserializeConverter1 () {
  415. JavaScriptSerializer serializer = new JavaScriptSerializer ();
  416. serializer.RegisterConverters (new JavaScriptConverter [] {
  417. new ListItemCollectionConverter() });
  418. ListBox ListBox1 = new ListBox ();
  419. ListBox1.Items.Add ("a1");
  420. ListBox1.Items.Add ("a2");
  421. ListBox1.Items.Add ("a3");
  422. string x = serializer.Serialize (ListBox1.Items);
  423. ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
  424. Assert.AreEqual (3, recoveredList.Count);
  425. }
  426. [Test]
  427. public void TestSerialize1 () {
  428. JavaScriptSerializer ser = new JavaScriptSerializer ();
  429. Assert.AreEqual("null", ser.Serialize(null));
  430. string js = ser.Serialize (1234);
  431. Assert.AreEqual ("1234", js);
  432. Assert.AreEqual (1234, ser.Deserialize<int> (js));
  433. js = ser.Serialize (1.1);
  434. Assert.AreEqual ("1.1", js);
  435. Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
  436. char [] chars = "faskjhfasd0981234".ToCharArray ();
  437. js = ser.Serialize (chars);
  438. char[] actual = ser.Deserialize<char[]> (js);
  439. Assert.AreEqual (chars.Length, actual.Length);
  440. for (int i = 0; i < chars.Length; i++)
  441. Assert.AreEqual (chars[i], actual[i]);
  442. 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{|}~""";
  443. 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{|}~";
  444. string serRes = ser.Serialize (data);
  445. Assert.AreEqual (expected, serRes);
  446. string deserRes = ser.Deserialize<string> (serRes);
  447. Assert.AreEqual (data, deserRes);
  448. }
  449. [Test]
  450. [ExpectedException (typeof (ArgumentNullException))]
  451. [Category ("NotDotNet")]
  452. public void TestSerialize2 () {
  453. JavaScriptSerializer ser = new JavaScriptSerializer ();
  454. ser.Serialize ("aaa", null);
  455. }
  456. static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
  457. [Test]
  458. public void TestSerializeDate () {
  459. JavaScriptSerializer ser = new JavaScriptSerializer ();
  460. DateTime now = new DateTime (633213894056010000L);
  461. string actual = ser.Serialize (now);
  462. DateTime dateTime = now.ToUniversalTime ();
  463. long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
  464. object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
  465. Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
  466. Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
  467. }
  468. [Test]
  469. public void TestSerializeEnum () {
  470. JavaScriptSerializer ser = new JavaScriptSerializer ();
  471. string result = ser.Serialize (MyEnum.BBB);
  472. Assert.AreEqual ("1", result);
  473. Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
  474. }
  475. class MyJavaScriptConverter : JavaScriptConverter
  476. {
  477. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  478. throw new Exception ("The method or operation is not implemented.");
  479. }
  480. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  481. Array a = (Array) obj;
  482. Dictionary<string, object> d = new Dictionary<string, object> ();
  483. d.Add ("0", 1);
  484. d.Add ("1", 2);
  485. return d;
  486. //throw new Exception ("The method or operation is not implemented.");
  487. }
  488. public override IEnumerable<Type> SupportedTypes {
  489. get {
  490. yield return typeof (X[]);
  491. }
  492. }
  493. }
  494. sealed class CultureInfoConverter : JavaScriptConverter
  495. {
  496. static readonly Type typeofCultureInfo = typeof (CultureInfo);
  497. public override IEnumerable<Type> SupportedTypes {
  498. get { yield return typeofCultureInfo; }
  499. }
  500. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  501. throw new NotSupportedException ();
  502. }
  503. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  504. CultureInfo ci = (CultureInfo)obj;
  505. if (ci == null)
  506. return null;
  507. Dictionary<string, object> d = new Dictionary<string, object> ();
  508. d.Add ("name", ci.Name);
  509. d.Add ("numberFormat", ci.NumberFormat);
  510. d.Add ("dateTimeFormat", ci.DateTimeFormat);
  511. return d;
  512. }
  513. }
  514. public class ListItemCollectionConverter : JavaScriptConverter
  515. {
  516. public override IEnumerable<Type> SupportedTypes {
  517. //Define the ListItemCollection as a supported type.
  518. get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
  519. }
  520. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  521. ListItemCollection listType = obj as ListItemCollection;
  522. if (listType != null) {
  523. // Create the representation.
  524. Dictionary<string, object> result = new Dictionary<string, object> ();
  525. ArrayList itemsList = new ArrayList ();
  526. foreach (ListItem item in listType) {
  527. //Add each entry to the dictionary.
  528. Dictionary<string, object> listDict = new Dictionary<string, object> ();
  529. listDict.Add ("Value", item.Value);
  530. listDict.Add ("Text", item.Text);
  531. itemsList.Add (listDict);
  532. }
  533. result ["List"] = itemsList;
  534. return result;
  535. }
  536. return new Dictionary<string, object> ();
  537. }
  538. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  539. if (dictionary == null)
  540. throw new ArgumentNullException ("dictionary");
  541. if (type == typeof (ListItemCollection)) {
  542. // Create the instance to deserialize into.
  543. ListItemCollection list = new ListItemCollection ();
  544. // Deserialize the ListItemCollection's items.
  545. ArrayList itemsList = (ArrayList) dictionary ["List"];
  546. for (int i = 0; i < itemsList.Count; i++)
  547. list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
  548. return list;
  549. }
  550. return null;
  551. }
  552. }
  553. [Test]
  554. public void DeserializeObject () {
  555. object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
  556. Assert.IsNotNull (o as Dictionary<string, object>, "type");
  557. Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
  558. Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
  559. Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
  560. object [] array = (object []) dictionary ["Array"];
  561. Assert.AreEqual (true, (bool) array [0], "array [0]");
  562. Assert.AreEqual (false, (bool) array [1], "array [1]");
  563. Assert.AreEqual (0, (int) array [2], "array [2]");
  564. }
  565. [Test]
  566. public void DeserializeObject2 ()
  567. {
  568. JavaScriptSerializer ser = new JavaScriptSerializer ();
  569. Y y = new Y ();
  570. string s = ser.Serialize (y);
  571. object y2 = ser.DeserializeObject (s);
  572. Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
  573. }
  574. [Test]
  575. public void DeserializeObject3 ()
  576. {
  577. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
  578. Y y = new Y ();
  579. string s = ser.Serialize (y);
  580. object y2 = ser.DeserializeObject (s);
  581. Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
  582. }
  583. [Test]
  584. public void DeserializeObject4 ()
  585. {
  586. JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
  587. Y y = new Y ();
  588. string s = ser.Serialize (y);
  589. object y2 = ser.DeserializeObject (s);
  590. Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
  591. Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
  592. Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
  593. Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
  594. Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
  595. }
  596. [Test]
  597. [ExpectedException(typeof(ArgumentNullException))]
  598. public void SerializeWithResolverDeserializeWithout ()
  599. {
  600. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  601. Y y = new Y ();
  602. string s = ser.Serialize (y);
  603. ser = new JavaScriptSerializer ();
  604. object y2 = ser.DeserializeObject (s);
  605. }
  606. [Test]
  607. public void SerializeWithoutResolverDeserializeWith ()
  608. {
  609. JavaScriptSerializer ser = new JavaScriptSerializer ();
  610. Y y = new Y ();
  611. string s = ser.Serialize (y);
  612. ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  613. object y2 = ser.DeserializeObject (s);
  614. Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
  615. }
  616. class B
  617. {
  618. public int v1 = 15;
  619. public string s1 = "s1";
  620. }
  621. class D : B
  622. {
  623. public int v2 = 16;
  624. public string s2 = "s2";
  625. }
  626. class C
  627. {
  628. public B b1 = new B ();
  629. public B b2 = new D ();
  630. }
  631. [Test]
  632. public void SerializeDerivedType ()
  633. {
  634. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  635. B b = new D ();
  636. string s = ser.Serialize (b);
  637. B b2 = ser.Deserialize<B> (s);
  638. Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
  639. }
  640. [Test]
  641. public void SerializeDerivedType2 ()
  642. {
  643. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  644. B b = new D ();
  645. string s = ser.Serialize (b);
  646. B b2 = (B)ser.DeserializeObject (s);
  647. Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
  648. }
  649. [Test]
  650. public void SerializeContainedDerivedType ()
  651. {
  652. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  653. C c = new C ();
  654. string s = ser.Serialize (c);
  655. C c2 = ser.Deserialize<C> (s);
  656. Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
  657. Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
  658. }
  659. [Test]
  660. public void SerializeContainedDerivedType2 ()
  661. {
  662. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  663. C c = new C ();
  664. string s = ser.Serialize (c);
  665. C c2 = (C)ser.DeserializeObject (s);
  666. Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
  667. Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
  668. }
  669. [Test]
  670. public void SerializeWithTypeConverter ()
  671. {
  672. JavaScriptSerializer ser = new JavaScriptSerializer ();
  673. MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  674. string s = ser.Serialize (uri);
  675. MyUri uri2 = ser.Deserialize<MyUri> (s);
  676. Assert.AreEqual (uri, uri2);
  677. }
  678. [Test]
  679. public void SerializeWithTypeConverter2 ()
  680. {
  681. JavaScriptSerializer ser = new JavaScriptSerializer ();
  682. MyPointContainer pc = new MyPointContainer(new Point(15, 16));
  683. string s = ser.Serialize(pc);
  684. MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
  685. }
  686. [Test]
  687. public void MaxJsonLengthDeserializeObject ()
  688. {
  689. JavaScriptSerializer ser = new JavaScriptSerializer ();
  690. ser.MaxJsonLength = 16;
  691. object o = ser.DeserializeObject ("{s:'1234567890'}");
  692. }
  693. [Test]
  694. [ExpectedException(typeof(ArgumentException))]
  695. public void MaxJsonLengthDeserializeObjectToLong ()
  696. {
  697. JavaScriptSerializer ser = new JavaScriptSerializer ();
  698. ser.MaxJsonLength = 15;
  699. object o = ser.DeserializeObject ("{s:'1234567890'}");
  700. }
  701. [Test]
  702. public void MaxJsonLengthSerialize ()
  703. {
  704. JavaScriptSerializer ser = new JavaScriptSerializer ();
  705. ser.MaxJsonLength = 9;
  706. Y y = new Y ();
  707. string s = ser.Serialize (y);
  708. }
  709. [Test]
  710. [ExpectedException (typeof (InvalidOperationException))]
  711. public void MaxJsonLengthSerializeToLong ()
  712. {
  713. JavaScriptSerializer ser = new JavaScriptSerializer ();
  714. ser.MaxJsonLength = 8;
  715. Y y = new Y ();
  716. string s = ser.Serialize (y);
  717. }
  718. [Test]
  719. public void RecursionLimitDeserialize1 ()
  720. {
  721. JavaScriptSerializer ser = new JavaScriptSerializer ();
  722. ser.RecursionLimit = 3;
  723. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  724. }
  725. [Test]
  726. public void RecursionLimitDeserialize2 ()
  727. {
  728. JavaScriptSerializer ser = new JavaScriptSerializer ();
  729. ser.RecursionLimit = 2;
  730. YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
  731. }
  732. [Test]
  733. public void RecursionLimitDeserialize3 ()
  734. {
  735. JavaScriptSerializer ser = new JavaScriptSerializer ();
  736. ser.RecursionLimit = 1;
  737. object o = ser.DeserializeObject ("\"xxx\"");
  738. }
  739. [Test]
  740. [ExpectedException(typeof(ArgumentException))]
  741. public void RecursionLimitDeserializeToDeap ()
  742. {
  743. JavaScriptSerializer ser = new JavaScriptSerializer ();
  744. ser.RecursionLimit = 2;
  745. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  746. }
  747. [Test]
  748. public void RecursionLimitSerialize ()
  749. {
  750. JavaScriptSerializer ser = new JavaScriptSerializer ();
  751. ser.RecursionLimit = 3;
  752. YY yy = new YY();
  753. string s = ser.Serialize (yy);
  754. }
  755. [Test]
  756. [ExpectedException(typeof(ArgumentException))]
  757. public void RecursionLimitSerializeToDeap ()
  758. {
  759. JavaScriptSerializer ser = new JavaScriptSerializer ();
  760. ser.RecursionLimit = 2;
  761. YY yy = new YY ();
  762. string s = ser.Serialize (yy);
  763. }
  764. [Test]
  765. public void RecursionLimitSerialize2 ()
  766. {
  767. JavaScriptSerializer ser = new JavaScriptSerializer ();
  768. ser.RecursionLimit = 2;
  769. YY yy = new YY ();
  770. StringBuilder b = new StringBuilder ();
  771. bool caughtException = false;
  772. try {
  773. ser.Serialize (yy, b);
  774. }
  775. catch {
  776. caughtException = true;
  777. }
  778. Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
  779. Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
  780. }
  781. [Test]
  782. public void SimpleTypeResolver ()
  783. {
  784. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  785. YY yy = new YY ();
  786. string s = ser.Serialize (yy);
  787. string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
  788. Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
  789. expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
  790. Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
  791. }
  792. public class CustomResolver : JavaScriptTypeResolver
  793. {
  794. public CustomResolver ()
  795. {
  796. Reset ();
  797. }
  798. public override Type ResolveType (string id)
  799. {
  800. ResolvedIds.Add (id);
  801. switch (id) {
  802. case "YY":
  803. return typeof(YY);
  804. case "Y":
  805. return typeof (Y);
  806. case "X":
  807. return typeof (X);
  808. case "int":
  809. return typeof (int);
  810. case "long":
  811. return typeof (long);
  812. case "string":
  813. return typeof (string);
  814. case "point":
  815. return typeof(Point);
  816. }
  817. return null;
  818. }
  819. public override string ResolveTypeId (Type type)
  820. {
  821. if (type == null) {
  822. throw new ArgumentNullException ("type");
  823. }
  824. ResolvedTypes.Add (type.Name);
  825. if (type == typeof (YY))
  826. return "YY";
  827. if (type == typeof (Y))
  828. return "Y";
  829. if (type == typeof (X))
  830. return "X";
  831. if (type == typeof (int))
  832. return "int";
  833. if (type == typeof (long))
  834. return "long";
  835. if (type == typeof (string))
  836. return "string";
  837. if (type == typeof(Point))
  838. return "point";
  839. return null;
  840. }
  841. public static List<string> ResolvedTypes {
  842. get {
  843. if (resolvedTypes == null) {
  844. resolvedTypes = new List<string> ();
  845. }
  846. return resolvedTypes;
  847. }
  848. }
  849. public static List<string> ResolvedIds {
  850. get {
  851. if (resolvedIds == null) {
  852. resolvedIds = new List<string> ();
  853. }
  854. return resolvedIds;
  855. }
  856. }
  857. public static void Reset ()
  858. {
  859. resolvedIds = null;
  860. resolvedTypes = null;
  861. }
  862. private static List<string> resolvedTypes;
  863. private static List<string> resolvedIds;
  864. }
  865. [Test]
  866. public void CustomTypeResolver ()
  867. {
  868. JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
  869. X x = new X ();
  870. x.Init ();
  871. string s = ser.Serialize (x);
  872. CustomResolver.Reset ();
  873. X x1 = (X) ser.DeserializeObject (s);
  874. Assert.IsTrue (x.Equals (x1), "x != x1");
  875. CustomResolver.Reset ();
  876. X x2 = ser.Deserialize<X> (s);
  877. Assert.IsTrue (x.Equals (x2), "x != x2");
  878. }
  879. }
  880. }