JavaScriptSerializerTest.cs 29 KB

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