JavaScriptSerializerTest.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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. namespace Tests.System.Web.Script.Serialization
  44. {
  45. [TestFixture]
  46. public class JavaScriptSerializerTest
  47. {
  48. enum MyEnum
  49. {
  50. AAA,
  51. BBB,
  52. CCC
  53. }
  54. #pragma warning disable 659
  55. class bug
  56. {
  57. //public DateTime dt;
  58. //public DateTime dt1;
  59. //public DateTime dt2;
  60. public bool bb;
  61. //Hashtable hash;
  62. public void Init() {
  63. //dt = DateTime.MaxValue;
  64. //dt1 = DateTime.MinValue;
  65. //dt2 = new DateTime ((DateTime.Now.Ticks / 10000) * 10000);
  66. bb = true;
  67. //hash = new Hashtable ();
  68. //hash.Add ("mykey", 1);
  69. }
  70. public override bool Equals (object obj) {
  71. if (!(obj is bug))
  72. return false;
  73. JavaScriptSerializerTest.FieldsEqual (this, obj);
  74. return true;
  75. }
  76. }
  77. class X
  78. {
  79. int x = 5;
  80. //int y;
  81. ulong _bb;
  82. Y[] _yy;
  83. Y [] _yyy = new Y [] { new Y (), new Y () };
  84. public int z;
  85. public char ch;
  86. public char ch_null;
  87. public string str;
  88. public byte b;
  89. public sbyte sb;
  90. public short sh;
  91. public ushort ush;
  92. public int i;
  93. public uint ui;
  94. public long l;
  95. public ulong ul;
  96. public float f;
  97. public float f1;
  98. public float f2;
  99. public float f3;
  100. public float f4;
  101. public double d;
  102. public double d1;
  103. public double d2;
  104. public double d3;
  105. public double d4;
  106. public decimal de;
  107. public decimal de1;
  108. public decimal de2;
  109. public decimal de3;
  110. public decimal de4;
  111. public Guid g;
  112. public Nullable<bool> nb;
  113. public DBNull dbn;
  114. IEnumerable<int> enum_int;
  115. IEnumerable enum_int1;
  116. public Uri uri;
  117. public Dictionary<string, Y> hash;
  118. public Point point;
  119. public void Init () {
  120. //y = 6;
  121. _bb = ulong.MaxValue - 5;
  122. _yy = new Y [] { new Y (), new Y () };
  123. z = 8;
  124. ch = (char) 0xFF56;
  125. ch_null = '\0';
  126. str = "\uFF56\uFF57\uF58FF59g";
  127. b = 253;
  128. sb = -48;
  129. sh = short.MinValue + 28;
  130. ush = ushort.MaxValue - 24;
  131. i = -234235453;
  132. ui = uint.MaxValue - 234234;
  133. l = long.MinValue + 28;
  134. ul = ulong.MaxValue - 3;
  135. f = float.NaN;
  136. f1 = float.NegativeInfinity;
  137. f2 = float.PositiveInfinity;
  138. f3 = float.MinValue;
  139. f4 = float.MaxValue;
  140. d = double.NaN;
  141. d1 = double.NegativeInfinity;
  142. d2 = double.PositiveInfinity;
  143. d3 = double.MinValue;
  144. d4 = double.MaxValue;
  145. de = decimal.MinusOne;
  146. de1 = decimal.Zero;
  147. de2 = decimal.One;
  148. de3 = decimal.MinValue;
  149. de4 = decimal.MaxValue;
  150. g = new Guid (234, 2, 354, new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 });
  151. nb = null;
  152. dbn = null;
  153. enum_int = new List<int> (MyEnum);
  154. enum_int1 = new ArrayList ();
  155. foreach (object obj in MyEnum1)
  156. ((ArrayList) enum_int1).Add (obj);
  157. uri = new Uri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  158. hash = new Dictionary<string, Y> ();
  159. Y y = new Y ();
  160. hash ["mykey"] = y;
  161. point = new Point (150, 150);
  162. }
  163. public IEnumerable<int> MyEnum {
  164. get {
  165. yield return 1;
  166. yield return 10;
  167. yield return 345;
  168. }
  169. set {
  170. enum_int = value;
  171. }
  172. }
  173. public IEnumerable MyEnum1 {
  174. get {
  175. yield return 1;
  176. yield return 10;
  177. yield return 345;
  178. }
  179. set {
  180. enum_int1 = value;
  181. }
  182. }
  183. public int AA {
  184. get { return x; }
  185. }
  186. public Y[] AA1 {
  187. get { return _yyy; }
  188. }
  189. public ulong BB {
  190. get { return _bb; }
  191. set { _bb = value; }
  192. }
  193. public Y[] YY {
  194. get { return _yy; }
  195. set { _yy = value; }
  196. }
  197. public override bool Equals (object obj) {
  198. if (!(obj is X))
  199. return false;
  200. JavaScriptSerializerTest.FieldsEqual (this, obj);
  201. return true;
  202. }
  203. }
  204. class Y
  205. {
  206. long _bb = 10;
  207. public long BB {
  208. get { return _bb; }
  209. set { _bb = value; }
  210. }
  211. public override bool Equals (object obj) {
  212. if (!(obj is Y))
  213. return false;
  214. JavaScriptSerializerTest.FieldsEqual(this, obj);
  215. return true;
  216. }
  217. }
  218. class YY
  219. {
  220. public YY ()
  221. {
  222. Y1 = new Y ();
  223. Y2 = new Y ();
  224. }
  225. public Y Y1;
  226. public Y Y2;
  227. }
  228. [TypeConverter (typeof (MyUriConverter))]
  229. class MyUri : Uri
  230. {
  231. public MyUri (string uriString, UriKind uriKind)
  232. : base (uriString, uriKind) {
  233. }
  234. public MyUri (Uri value)
  235. : base (value.AbsoluteUri) {
  236. }
  237. }
  238. class MyUriConverter : UriTypeConverter
  239. {
  240. public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  241. {
  242. return base.ConvertTo (context, culture, value, destinationType);
  243. }
  244. public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
  245. {
  246. Uri convertedUri = (Uri)base.ConvertFrom (context, culture, value);
  247. return new MyUri (convertedUri);
  248. }
  249. }
  250. [TypeConverter(typeof(MyPointConverter))]
  251. class MyPointContainer
  252. {
  253. public MyPointContainer ()
  254. {
  255. }
  256. public MyPointContainer (Point v)
  257. {
  258. p = v;
  259. }
  260. internal Point p;
  261. }
  262. class MyPointConverter : TypeConverter
  263. {
  264. public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
  265. {
  266. if (destinationType == typeof (string)) {
  267. return true;
  268. }
  269. return base.CanConvertTo (context, destinationType);
  270. }
  271. public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
  272. {
  273. if (destinationType == typeof (string)) {
  274. MyPointContainer pc = (MyPointContainer) value;
  275. return pc.p.X + "," + pc.p.Y;
  276. }
  277. return base.ConvertTo (context, culture, value, destinationType);
  278. }
  279. public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
  280. {
  281. if (sourceType == typeof (string)) {
  282. return true;
  283. }
  284. return base.CanConvertFrom (context, sourceType);
  285. }
  286. public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
  287. {
  288. if (value is string) {
  289. string [] v = ((string) value).Split (new char [] { ',' });
  290. return new MyPointContainer(new Point (int.Parse (v [0]), int.Parse (v [1])));
  291. }
  292. return base.ConvertFrom (context, culture, value);
  293. }
  294. }
  295. #pragma warning restore 659
  296. [Test]
  297. [Category ("NotDotNet")]
  298. public void TestDefaults () {
  299. JavaScriptSerializer ser = new JavaScriptSerializer ();
  300. Assert.AreEqual (102400, ser.MaxJsonLength);
  301. Assert.AreEqual (100, ser.RecursionLimit);
  302. //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
  303. //l.Add (new MyJavaScriptConverter ());
  304. //ser.RegisterConverters (l);
  305. //string x = ser.Serialize (new X [] { new X (), new X () });
  306. //string s = ser.Serialize (new X());
  307. //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
  308. //X x = ser.Deserialize<X> (s);
  309. //object ddd = typeof (Y).GetMember ("BB");
  310. //object x1 = ser.Deserialize<X []> (null);
  311. //object x2 = ser.Deserialize<X []> ("");
  312. //object d = ser.Deserialize<X[]> (x);
  313. }
  314. [Test]
  315. public void TestDeserialize () {
  316. JavaScriptSerializer ser = new JavaScriptSerializer ();
  317. Assert.IsNull (ser.Deserialize<X> (""));
  318. X s = new X ();
  319. s.Init ();
  320. string x = ser.Serialize (s);
  321. X n = ser.Deserialize<X> (x);
  322. Assert.AreEqual (s, n);
  323. //string json = "\\uFF56";
  324. //string result = ser.Deserialize<string> (json);
  325. //Assert.AreEqual ("\uFF56", result);
  326. //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
  327. }
  328. [Test]
  329. public void TestDeserializeTypeResolver ()
  330. {
  331. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  332. X x = new X ();
  333. x.Init ();
  334. string s = ser.Serialize (x);
  335. X x2 = ser.Deserialize<X> (s);
  336. Assert.AreEqual (x, x2);
  337. }
  338. [Test]
  339. [Category("NotWorking")]
  340. public void TestDeserializeBugs () {
  341. JavaScriptSerializer ser = new JavaScriptSerializer ();
  342. bug s = new bug ();
  343. s.Init ();
  344. string x = ser.Serialize (s);
  345. bug n = ser.Deserialize<bug> (x);
  346. Assert.AreEqual (s, n);
  347. // Should check correctness with .Net GA:
  348. //js = ser.Serialize (Color.Red);
  349. //Color ccc = ser.Deserialize<Color> (js);
  350. //string xml = @"<root><node attr=""xxx""/></root>";
  351. //XmlDocument doc = new XmlDocument ();
  352. //doc.LoadXml (xml);
  353. //string js = ser.Serialize (doc);
  354. //DataTable table = new DataTable();
  355. //table.Columns.Add ("col1", typeof (int));
  356. //table.Columns.Add ("col2", typeof (float));
  357. //table.Rows.Add (1, 1f);
  358. //table.Rows.Add (234234, 2.4f);
  359. //string js = ser.Serialize (table);
  360. }
  361. static void FieldsEqual (object expected, object actual) {
  362. Assert.AreEqual (expected.GetType (), actual.GetType ());
  363. FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
  364. foreach (FieldInfo info in infos) {
  365. object value1 = info.GetValue (expected);
  366. object value2 = info.GetValue (actual);
  367. if (value1 is IEnumerable) {
  368. IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
  369. int index = -1;
  370. foreach (object x in (IEnumerable) value1) {
  371. if (!yenum.MoveNext ())
  372. Assert.Fail (info.Name + " index:" + index);
  373. index++;
  374. if (x is DictionaryEntry) {
  375. DictionaryEntry entry = (DictionaryEntry)x;
  376. IDictionary dict = (IDictionary) value2;
  377. Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
  378. }
  379. else
  380. Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
  381. }
  382. Assert.IsFalse (yenum.MoveNext (), info.Name);
  383. continue;
  384. }
  385. Assert.AreEqual (value1, value2, info.Name);
  386. }
  387. }
  388. [Test]
  389. [ExpectedException (typeof (ArgumentNullException))]
  390. public void TestDeserialize1 () {
  391. JavaScriptSerializer ser = new JavaScriptSerializer ();
  392. ser.Deserialize<string> (null);
  393. }
  394. [Test]
  395. [ExpectedException (typeof (ArgumentNullException))]
  396. public void TestDeserializeNullConverter () {
  397. JavaScriptSerializer ser = new JavaScriptSerializer ();
  398. ser.RegisterConverters (null);
  399. }
  400. [Test]
  401. public void TestDeserializeConverter () {
  402. JavaScriptSerializer ser = new JavaScriptSerializer ();
  403. List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
  404. list.Add (new MyJavaScriptConverter ());
  405. list.Add (new CultureInfoConverter ());
  406. ser.RegisterConverters (list);
  407. string result = ser.Serialize (new X [] { new X (), new X () });
  408. Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
  409. result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
  410. }
  411. [Test]
  412. public void TestSerialize1 () {
  413. JavaScriptSerializer ser = new JavaScriptSerializer ();
  414. Assert.AreEqual("null", ser.Serialize(null));
  415. string js = ser.Serialize (1234);
  416. Assert.AreEqual ("1234", js);
  417. Assert.AreEqual (1234, ser.Deserialize<int> (js));
  418. js = ser.Serialize (1.1);
  419. Assert.AreEqual ("1.1", js);
  420. Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
  421. char [] chars = "faskjhfasd0981234".ToCharArray ();
  422. js = ser.Serialize (chars);
  423. char[] actual = ser.Deserialize<char[]> (js);
  424. Assert.AreEqual (chars.Length, actual.Length);
  425. for (int i = 0; i < chars.Length; i++)
  426. Assert.AreEqual (chars[i], actual[i]);
  427. 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{|}~""";
  428. 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{|}~";
  429. string serRes = ser.Serialize (data);
  430. Assert.AreEqual (expected, serRes);
  431. string deserRes = ser.Deserialize<string> (serRes);
  432. Assert.AreEqual (data, deserRes);
  433. }
  434. [Test]
  435. [ExpectedException (typeof (ArgumentNullException))]
  436. [Category ("NotDotNet")]
  437. public void TestSerialize2 () {
  438. JavaScriptSerializer ser = new JavaScriptSerializer ();
  439. ser.Serialize ("aaa", null);
  440. }
  441. static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
  442. [Test]
  443. public void TestSerializeDate () {
  444. JavaScriptSerializer ser = new JavaScriptSerializer ();
  445. DateTime now = new DateTime (633213894056010000L);
  446. string actual = ser.Serialize (now);
  447. DateTime dateTime = now.ToUniversalTime ();
  448. long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
  449. object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
  450. Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
  451. Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
  452. }
  453. [Test]
  454. public void TestSerializeEnum () {
  455. JavaScriptSerializer ser = new JavaScriptSerializer ();
  456. string result = ser.Serialize (MyEnum.BBB);
  457. Assert.AreEqual ("1", result);
  458. Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
  459. }
  460. class MyJavaScriptConverter : JavaScriptConverter
  461. {
  462. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  463. throw new Exception ("The method or operation is not implemented.");
  464. }
  465. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  466. Array a = (Array) obj;
  467. Dictionary<string, object> d = new Dictionary<string, object> ();
  468. d.Add ("0", 1);
  469. d.Add ("1", 2);
  470. return d;
  471. //throw new Exception ("The method or operation is not implemented.");
  472. }
  473. public override IEnumerable<Type> SupportedTypes {
  474. get {
  475. yield return typeof (X[]);
  476. }
  477. }
  478. }
  479. sealed class CultureInfoConverter : JavaScriptConverter
  480. {
  481. static readonly Type typeofCultureInfo = typeof (CultureInfo);
  482. public override IEnumerable<Type> SupportedTypes {
  483. get { yield return typeofCultureInfo; }
  484. }
  485. public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
  486. throw new NotSupportedException ();
  487. }
  488. public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
  489. CultureInfo ci = (CultureInfo)obj;
  490. if (ci == null)
  491. return null;
  492. Dictionary<string, object> d = new Dictionary<string, object> ();
  493. d.Add ("name", ci.Name);
  494. d.Add ("numberFormat", ci.NumberFormat);
  495. d.Add ("dateTimeFormat", ci.DateTimeFormat);
  496. return d;
  497. }
  498. }
  499. [Test]
  500. public void DeserializeObject () {
  501. object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
  502. Assert.IsNotNull (o as Dictionary<string, object>, "type");
  503. Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
  504. Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
  505. Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
  506. object [] array = (object []) dictionary ["Array"];
  507. Assert.AreEqual (true, (bool) array [0], "array [0]");
  508. Assert.AreEqual (false, (bool) array [1], "array [1]");
  509. Assert.AreEqual (0, (int) array [2], "array [2]");
  510. }
  511. [Test]
  512. public void DeserializeObject2 ()
  513. {
  514. JavaScriptSerializer ser = new JavaScriptSerializer ();
  515. Y y = new Y ();
  516. string s = ser.Serialize (y);
  517. object y2 = ser.DeserializeObject (s);
  518. Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
  519. }
  520. [Test]
  521. public void DeserializeObject3 ()
  522. {
  523. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
  524. Y y = new Y ();
  525. string s = ser.Serialize (y);
  526. object y2 = ser.DeserializeObject (s);
  527. Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
  528. }
  529. [Test]
  530. public void DeserializeObject4 ()
  531. {
  532. JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
  533. Y y = new Y ();
  534. string s = ser.Serialize (y);
  535. object y2 = ser.DeserializeObject (s);
  536. Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
  537. Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
  538. Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
  539. Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
  540. Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
  541. }
  542. [Test]
  543. [ExpectedException(typeof(ArgumentNullException))]
  544. public void SerializeWithResolverDeserializeWithout ()
  545. {
  546. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  547. Y y = new Y ();
  548. string s = ser.Serialize (y);
  549. ser = new JavaScriptSerializer ();
  550. object y2 = ser.DeserializeObject (s);
  551. }
  552. [Test]
  553. public void SerializeWithoutResolverDeserializeWith ()
  554. {
  555. JavaScriptSerializer ser = new JavaScriptSerializer ();
  556. Y y = new Y ();
  557. string s = ser.Serialize (y);
  558. ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  559. object y2 = ser.DeserializeObject (s);
  560. Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
  561. }
  562. class B
  563. {
  564. public int v1 = 15;
  565. public string s1 = "s1";
  566. }
  567. class D : B
  568. {
  569. public int v2 = 16;
  570. public string s2 = "s2";
  571. }
  572. class C
  573. {
  574. public B b1 = new B ();
  575. public B b2 = new D ();
  576. }
  577. [Test]
  578. public void SerializeDerivedType ()
  579. {
  580. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  581. B b = new D ();
  582. string s = ser.Serialize (b);
  583. B b2 = ser.Deserialize<B> (s);
  584. Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
  585. }
  586. [Test]
  587. public void SerializeDerivedType2 ()
  588. {
  589. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  590. B b = new D ();
  591. string s = ser.Serialize (b);
  592. B b2 = (B)ser.DeserializeObject (s);
  593. Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
  594. }
  595. [Test]
  596. public void SerializeContainedDerivedType ()
  597. {
  598. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  599. C c = new C ();
  600. string s = ser.Serialize (c);
  601. C c2 = ser.Deserialize<C> (s);
  602. Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
  603. Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
  604. }
  605. [Test]
  606. public void SerializeContainedDerivedType2 ()
  607. {
  608. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  609. C c = new C ();
  610. string s = ser.Serialize (c);
  611. C c2 = (C)ser.DeserializeObject (s);
  612. Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
  613. Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
  614. }
  615. [Test]
  616. public void SerializeWithTypeConverter ()
  617. {
  618. JavaScriptSerializer ser = new JavaScriptSerializer ();
  619. MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
  620. string s = ser.Serialize (uri);
  621. MyUri uri2 = ser.Deserialize<MyUri> (s);
  622. Assert.AreEqual (uri, uri2);
  623. }
  624. [Test]
  625. public void SerializeWithTypeConverter2 ()
  626. {
  627. JavaScriptSerializer ser = new JavaScriptSerializer ();
  628. MyPointContainer pc = new MyPointContainer(new Point(15, 16));
  629. string s = ser.Serialize(pc);
  630. MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
  631. }
  632. [Test]
  633. public void MaxJsonLengthDeserializeObject ()
  634. {
  635. JavaScriptSerializer ser = new JavaScriptSerializer ();
  636. ser.MaxJsonLength = 16;
  637. object o = ser.DeserializeObject ("{s:'1234567890'}");
  638. }
  639. [Test]
  640. [ExpectedException(typeof(ArgumentException))]
  641. public void MaxJsonLengthDeserializeObjectToLong ()
  642. {
  643. JavaScriptSerializer ser = new JavaScriptSerializer ();
  644. ser.MaxJsonLength = 15;
  645. object o = ser.DeserializeObject ("{s:'1234567890'}");
  646. }
  647. [Test]
  648. public void MaxJsonLengthSerialize ()
  649. {
  650. JavaScriptSerializer ser = new JavaScriptSerializer ();
  651. ser.MaxJsonLength = 9;
  652. Y y = new Y ();
  653. string s = ser.Serialize (y);
  654. }
  655. [Test]
  656. [ExpectedException (typeof (InvalidOperationException), "Maximum length exceeded.")]
  657. public void MaxJsonLengthSerializeToLong ()
  658. {
  659. JavaScriptSerializer ser = new JavaScriptSerializer ();
  660. ser.MaxJsonLength = 8;
  661. Y y = new Y ();
  662. string s = ser.Serialize (y);
  663. }
  664. [Test]
  665. public void RecursionLimitDeserialize1 ()
  666. {
  667. JavaScriptSerializer ser = new JavaScriptSerializer ();
  668. ser.RecursionLimit = 3;
  669. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  670. }
  671. [Test]
  672. public void RecursionLimitDeserialize2 ()
  673. {
  674. JavaScriptSerializer ser = new JavaScriptSerializer ();
  675. ser.RecursionLimit = 2;
  676. YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
  677. }
  678. [Test]
  679. public void RecursionLimitDeserialize3 ()
  680. {
  681. JavaScriptSerializer ser = new JavaScriptSerializer ();
  682. ser.RecursionLimit = 1;
  683. object o = ser.DeserializeObject ("\"xxx\"");
  684. }
  685. [Test]
  686. [ExpectedException(typeof(ArgumentException))]
  687. public void RecursionLimitDeserializeToDeap ()
  688. {
  689. JavaScriptSerializer ser = new JavaScriptSerializer ();
  690. ser.RecursionLimit = 2;
  691. YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
  692. }
  693. [Test]
  694. public void RecursionLimitSerialize ()
  695. {
  696. JavaScriptSerializer ser = new JavaScriptSerializer ();
  697. ser.RecursionLimit = 3;
  698. YY yy = new YY();
  699. string s = ser.Serialize (yy);
  700. }
  701. [Test]
  702. [ExpectedException(typeof(ArgumentException))]
  703. public void RecursionLimitSerializeToDeap ()
  704. {
  705. JavaScriptSerializer ser = new JavaScriptSerializer ();
  706. ser.RecursionLimit = 2;
  707. YY yy = new YY ();
  708. string s = ser.Serialize (yy);
  709. }
  710. [Test]
  711. public void RecursionLimitSerialize2 ()
  712. {
  713. JavaScriptSerializer ser = new JavaScriptSerializer ();
  714. ser.RecursionLimit = 2;
  715. YY yy = new YY ();
  716. StringBuilder b = new StringBuilder ();
  717. bool caughtException = false;
  718. try {
  719. ser.Serialize (yy, b);
  720. }
  721. catch {
  722. caughtException = true;
  723. }
  724. Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
  725. Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
  726. }
  727. [Test]
  728. public void SimpleTypeResolver ()
  729. {
  730. JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
  731. YY yy = new YY ();
  732. string s = ser.Serialize (yy);
  733. string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
  734. Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
  735. expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
  736. Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
  737. }
  738. public class CustomResolver : JavaScriptTypeResolver
  739. {
  740. public CustomResolver ()
  741. {
  742. Reset ();
  743. }
  744. public override Type ResolveType (string id)
  745. {
  746. ResolvedIds.Add (id);
  747. switch (id) {
  748. case "YY":
  749. return typeof(YY);
  750. case "Y":
  751. return typeof (Y);
  752. case "X":
  753. return typeof (X);
  754. case "int":
  755. return typeof (int);
  756. case "long":
  757. return typeof (long);
  758. case "string":
  759. return typeof (string);
  760. case "point":
  761. return typeof(Point);
  762. }
  763. return null;
  764. }
  765. public override string ResolveTypeId (Type type)
  766. {
  767. if (type == null) {
  768. throw new ArgumentNullException ("type");
  769. }
  770. ResolvedTypes.Add (type.Name);
  771. if (type == typeof (YY))
  772. return "YY";
  773. if (type == typeof (Y))
  774. return "Y";
  775. if (type == typeof (X))
  776. return "X";
  777. if (type == typeof (int))
  778. return "int";
  779. if (type == typeof (long))
  780. return "long";
  781. if (type == typeof (string))
  782. return "string";
  783. if (type == typeof(Point))
  784. return "point";
  785. return null;
  786. }
  787. public static List<string> ResolvedTypes {
  788. get {
  789. if (resolvedTypes == null) {
  790. resolvedTypes = new List<string> ();
  791. }
  792. return resolvedTypes;
  793. }
  794. }
  795. public static List<string> ResolvedIds {
  796. get {
  797. if (resolvedIds == null) {
  798. resolvedIds = new List<string> ();
  799. }
  800. return resolvedIds;
  801. }
  802. }
  803. public static void Reset ()
  804. {
  805. resolvedIds = null;
  806. resolvedTypes = null;
  807. }
  808. private static List<string> resolvedTypes;
  809. private static List<string> resolvedIds;
  810. }
  811. [Test]
  812. public void CustomTypeResolver ()
  813. {
  814. JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
  815. X x = new X ();
  816. x.Init ();
  817. string s = ser.Serialize (x);
  818. CustomResolver.Reset ();
  819. X x1 = (X) ser.DeserializeObject (s);
  820. Assert.IsTrue (x.Equals (x1), "x != x1");
  821. CustomResolver.Reset ();
  822. X x2 = ser.Deserialize<X> (s);
  823. Assert.IsTrue (x.Equals (x2), "x != x2");
  824. }
  825. }
  826. }