2 // JavaScriptSerializer.cs
5 // Konstantin Triger <kostat@mainsoft.com>
7 // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
31 using System.Collections.Generic;
33 using NUnit.Framework;
34 using System.Web.Script.Serialization;
35 using System.Reflection;
36 using System.Collections;
38 using ComponentModel = System.ComponentModel;
39 using System.Globalization;
40 using System.Threading;
41 using System.Text.RegularExpressions;
42 using System.ComponentModel;
43 using CategoryAttribute = NUnit.Framework.CategoryAttribute;
44 using System.Web.UI.WebControls;
45 using System.Collections.ObjectModel;
48 namespace Tests.System.Web.Script.Serialization
51 public class JavaScriptSerializerTest
59 #pragma warning disable 659
63 //public DateTime dt1;
64 //public DateTime dt2;
69 //dt = DateTime.MaxValue;
70 //dt1 = DateTime.MinValue;
71 //dt2 = new DateTime ((DateTime.Now.Ticks / 10000) * 10000);
73 //hash = new Hashtable ();
74 //hash.Add ("mykey", 1);
77 public override bool Equals (object obj) {
80 JavaScriptSerializerTest.FieldsEqual (this, obj);
90 Y [] _yyy = new Y [] { new Y (), new Y () };
126 public Nullable<bool> nb;
128 IEnumerable<int> enum_int;
129 IEnumerable enum_int1;
131 public Dictionary<string, Y> hash;
134 public void Init () {
136 _bb = ulong.MaxValue - 5;
137 _yy = new Y [] { new Y (), new Y () };
141 str = "\uFF56\uFF57\uF58FF59g";
144 sh = short.MinValue + 28;
145 ush = ushort.MaxValue - 24;
147 ui = uint.MaxValue - 234234;
148 l = long.MinValue + 28;
149 ul = ulong.MaxValue - 3;
152 f1 = float.NegativeInfinity;
153 f2 = float.PositiveInfinity;
158 d1 = double.NegativeInfinity;
159 d2 = double.PositiveInfinity;
160 d3 = double.MinValue;
161 d4 = double.MaxValue;
163 de = decimal.MinusOne;
166 de3 = decimal.MinValue;
167 de4 = decimal.MaxValue;
169 g = new Guid (234, 2, 354, new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 });
174 enum_int = new List<int> (MyEnum);
175 enum_int1 = new ArrayList ();
176 foreach (object obj in MyEnum1)
177 ((ArrayList) enum_int1).Add (obj);
178 uri = new Uri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
180 hash = new Dictionary<string, Y> ();
183 point = new Point (150, 150);
186 public IEnumerable<int> MyEnum {
198 public IEnumerable MyEnum1 {
228 public override bool Equals (object obj) {
231 JavaScriptSerializerTest.FieldsEqual (this, obj);
246 public override bool Equals (object obj) {
249 JavaScriptSerializerTest.FieldsEqual(this, obj);
266 [TypeConverter (typeof (MyUriConverter))]
269 public MyUri (string uriString, UriKind uriKind)
270 : base (uriString, uriKind) {
273 public MyUri (Uri value)
274 : base (value.AbsoluteUri) {
278 class MyUriConverter : UriTypeConverter
280 public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
282 return base.ConvertTo (context, culture, value, destinationType);
285 public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
287 Uri convertedUri = (Uri)base.ConvertFrom (context, culture, value);
288 return new MyUri (convertedUri);
292 [TypeConverter(typeof(MyPointConverter))]
293 class MyPointContainer
295 public MyPointContainer ()
299 public MyPointContainer (Point v)
307 class MyPointConverter : TypeConverter
309 public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType)
311 if (destinationType == typeof (string)) {
314 return base.CanConvertTo (context, destinationType);
317 public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
319 if (destinationType == typeof (string)) {
320 MyPointContainer pc = (MyPointContainer) value;
321 return pc.p.X + "," + pc.p.Y;
323 return base.ConvertTo (context, culture, value, destinationType);
326 public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType)
328 if (sourceType == typeof (string)) {
331 return base.CanConvertFrom (context, sourceType);
334 public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value)
336 if (value is string) {
337 string [] v = ((string) value).Split (new char [] { ',' });
338 return new MyPointContainer(new Point (int.Parse (v [0]), int.Parse (v [1])));
340 return base.ConvertFrom (context, culture, value);
344 #pragma warning restore 659
347 [Category ("NotDotNet")]
348 public void TestDefaults () {
349 JavaScriptSerializer ser = new JavaScriptSerializer ();
350 Assert.AreEqual (102400, ser.MaxJsonLength);
351 Assert.AreEqual (100, ser.RecursionLimit);
352 //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
353 //l.Add (new MyJavaScriptConverter ());
354 //ser.RegisterConverters (l);
355 //string x = ser.Serialize (new X [] { new X (), new X () });
356 //string s = ser.Serialize (new X());
357 //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
358 //X x = ser.Deserialize<X> (s);
359 //object ddd = typeof (Y).GetMember ("BB");
360 //object x1 = ser.Deserialize<X []> (null);
361 //object x2 = ser.Deserialize<X []> ("");
362 //object d = ser.Deserialize<X[]> (x);
366 public void TestDeserialize () {
367 JavaScriptSerializer ser = new JavaScriptSerializer ();
368 Assert.IsNull (ser.Deserialize<X> (""));
372 string x = ser.Serialize (s);
373 X n = ser.Deserialize<X> (x);
374 Assert.AreEqual (s, n);
376 //string json = "\\uFF56";
377 //string result = ser.Deserialize<string> (json);
378 //Assert.AreEqual ("\uFF56", result);
380 //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
384 public void TestDeserializeTypeResolver ()
386 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
390 string s = ser.Serialize (x);
391 X x2 = ser.Deserialize<X> (s);
392 Assert.AreEqual (x, x2);
396 [Category("NotWorking")]
397 public void TestDeserializeBugs () {
398 JavaScriptSerializer ser = new JavaScriptSerializer ();
402 string x = ser.Serialize (s);
403 bug n = ser.Deserialize<bug> (x);
404 Assert.AreEqual (s, n);
406 // Should check correctness with .Net GA:
407 //js = ser.Serialize (Color.Red);
408 //Color ccc = ser.Deserialize<Color> (js);
409 //string xml = @"<root><node attr=""xxx""/></root>";
411 //XmlDocument doc = new XmlDocument ();
413 //string js = ser.Serialize (doc);
414 //DataTable table = new DataTable();
415 //table.Columns.Add ("col1", typeof (int));
416 //table.Columns.Add ("col2", typeof (float));
417 //table.Rows.Add (1, 1f);
418 //table.Rows.Add (234234, 2.4f);
420 //string js = ser.Serialize (table);
423 static void FieldsEqual (object expected, object actual) {
424 Assert.AreEqual (expected.GetType (), actual.GetType ());
425 FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
426 foreach (FieldInfo info in infos) {
427 object value1 = info.GetValue (expected);
428 object value2 = info.GetValue (actual);
429 if (value1 is IEnumerable) {
430 IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
432 foreach (object x in (IEnumerable) value1) {
433 if (!yenum.MoveNext ())
434 Assert.Fail (info.Name + " index:" + index);
436 if (x is DictionaryEntry) {
437 DictionaryEntry entry = (DictionaryEntry)x;
438 IDictionary dict = (IDictionary) value2;
439 Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
442 Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
444 Assert.IsFalse (yenum.MoveNext (), info.Name);
447 Assert.AreEqual (value1, value2, info.Name);
453 [ExpectedException (typeof (ArgumentNullException))]
454 public void TestDeserialize1 () {
455 JavaScriptSerializer ser = new JavaScriptSerializer ();
456 ser.Deserialize<string> (null);
460 [ExpectedException (typeof (ArgumentNullException))]
461 public void TestDeserializeNullConverter () {
462 JavaScriptSerializer ser = new JavaScriptSerializer ();
463 ser.RegisterConverters (null);
467 public void TestDeserializeConverter () {
468 JavaScriptSerializer ser = new JavaScriptSerializer ();
469 List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
470 list.Add (new MyJavaScriptConverter ());
471 list.Add (new CultureInfoConverter ());
472 ser.RegisterConverters (list);
473 string result = ser.Serialize (new X [] { new X (), new X () });
474 Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
475 result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
479 public void TestDeserializeConverter1 () {
480 JavaScriptSerializer serializer = new JavaScriptSerializer ();
482 serializer.RegisterConverters (new JavaScriptConverter [] {
483 new ListItemCollectionConverter() });
485 ListBox ListBox1 = new ListBox ();
486 ListBox1.Items.Add ("a1");
487 ListBox1.Items.Add ("a2");
488 ListBox1.Items.Add ("a3");
490 string x = serializer.Serialize (ListBox1.Items);
491 ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
492 Assert.AreEqual (3, recoveredList.Count);
496 public void TestSerialize1 () {
497 JavaScriptSerializer ser = new JavaScriptSerializer ();
498 Assert.AreEqual("null", ser.Serialize(null));
500 string js = ser.Serialize (1234);
501 Assert.AreEqual ("1234", js);
502 Assert.AreEqual (1234, ser.Deserialize<int> (js));
503 js = ser.Serialize (1.1);
504 Assert.AreEqual ("1.1", js);
505 Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
506 char [] chars = "faskjhfasd0981234".ToCharArray ();
507 js = ser.Serialize (chars);
508 char[] actual = ser.Deserialize<char[]> (js);
509 Assert.AreEqual (chars.Length, actual.Length);
510 for (int i = 0; i < chars.Length; i++)
511 Assert.AreEqual (chars[i], actual[i]);
513 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{|}~""";
514 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{|}~";
516 string serRes = ser.Serialize (data);
517 Assert.AreEqual (expected, serRes);
518 string deserRes = ser.Deserialize<string> (serRes);
519 Assert.AreEqual (data, deserRes);
523 [ExpectedException (typeof (ArgumentNullException))]
524 [Category ("NotDotNet")]
525 public void TestSerialize2 () {
526 JavaScriptSerializer ser = new JavaScriptSerializer ();
527 ser.Serialize ("aaa", null);
530 static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
533 public void TestSerializeDate () {
534 JavaScriptSerializer ser = new JavaScriptSerializer ();
535 DateTime now = new DateTime (633213894056010000L);
537 string actual = ser.Serialize (now);
538 DateTime dateTime = now.ToUniversalTime ();
539 long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
541 object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
542 Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
543 Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
547 public void TestSerializeEnum () {
548 JavaScriptSerializer ser = new JavaScriptSerializer ();
549 string result = ser.Serialize (MyEnum.BBB);
550 Assert.AreEqual ("1", result);
551 Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
554 class MyJavaScriptConverter : JavaScriptConverter
556 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
557 throw new Exception ("The method or operation is not implemented.");
560 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
561 Array a = (Array) obj;
562 Dictionary<string, object> d = new Dictionary<string, object> ();
566 //throw new Exception ("The method or operation is not implemented.");
569 public override IEnumerable<Type> SupportedTypes {
571 yield return typeof (X[]);
576 sealed class CultureInfoConverter : JavaScriptConverter
578 static readonly Type typeofCultureInfo = typeof (CultureInfo);
579 public override IEnumerable<Type> SupportedTypes {
580 get { yield return typeofCultureInfo; }
583 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
584 throw new NotSupportedException ();
587 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
588 CultureInfo ci = (CultureInfo)obj;
591 Dictionary<string, object> d = new Dictionary<string, object> ();
592 d.Add ("name", ci.Name);
593 d.Add ("numberFormat", ci.NumberFormat);
594 d.Add ("dateTimeFormat", ci.DateTimeFormat);
599 public class ListItemCollectionConverter : JavaScriptConverter
601 public override IEnumerable<Type> SupportedTypes {
602 //Define the ListItemCollection as a supported type.
603 get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
606 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
607 ListItemCollection listType = obj as ListItemCollection;
609 if (listType != null) {
610 // Create the representation.
611 Dictionary<string, object> result = new Dictionary<string, object> ();
612 ArrayList itemsList = new ArrayList ();
613 foreach (ListItem item in listType) {
614 //Add each entry to the dictionary.
615 Dictionary<string, object> listDict = new Dictionary<string, object> ();
616 listDict.Add ("Value", item.Value);
617 listDict.Add ("Text", item.Text);
618 itemsList.Add (listDict);
620 result ["List"] = itemsList;
624 return new Dictionary<string, object> ();
627 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
628 if (dictionary == null)
629 throw new ArgumentNullException ("dictionary");
631 if (type == typeof (ListItemCollection)) {
632 // Create the instance to deserialize into.
633 ListItemCollection list = new ListItemCollection ();
635 // Deserialize the ListItemCollection's items.
636 ArrayList itemsList = (ArrayList) dictionary ["List"];
637 for (int i = 0; i < itemsList.Count; i++)
638 list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
647 public void DeserializeObject () {
648 object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
649 Assert.IsNotNull (o as Dictionary<string, object>, "type");
650 Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
651 Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
652 Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
653 object [] array = (object []) dictionary ["Array"];
654 Assert.AreEqual (true, (bool) array [0], "array [0]");
655 Assert.AreEqual (false, (bool) array [1], "array [1]");
656 Assert.AreEqual (0, (int) array [2], "array [2]");
660 public void DeserializeObject2 ()
662 JavaScriptSerializer ser = new JavaScriptSerializer ();
664 string s = ser.Serialize (y);
665 object y2 = ser.DeserializeObject (s);
666 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
670 public void DeserializeObject3 ()
672 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
674 string s = ser.Serialize (y);
675 object y2 = ser.DeserializeObject (s);
676 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
680 public void DeserializeObject4 ()
682 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
684 string s = ser.Serialize (y);
685 object y2 = ser.DeserializeObject (s);
686 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
687 Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
688 Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
689 Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
690 Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
694 [ExpectedException(typeof(ArgumentNullException))]
695 public void SerializeWithResolverDeserializeWithout ()
697 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
699 string s = ser.Serialize (y);
700 ser = new JavaScriptSerializer ();
701 object y2 = ser.DeserializeObject (s);
705 public void SerializeWithoutResolverDeserializeWith ()
707 JavaScriptSerializer ser = new JavaScriptSerializer ();
709 string s = ser.Serialize (y);
710 ser = new JavaScriptSerializer (new SimpleTypeResolver ());
711 object y2 = ser.DeserializeObject (s);
712 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
718 public string s1 = "s1";
724 public string s2 = "s2";
729 public B b1 = new B ();
730 public B b2 = new D ();
734 public void SerializeDerivedType ()
736 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
738 string s = ser.Serialize (b);
739 B b2 = ser.Deserialize<B> (s);
740 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
744 public void SerializeDerivedType2 ()
746 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
748 string s = ser.Serialize (b);
749 B b2 = (B)ser.DeserializeObject (s);
750 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
754 public void SerializeContainedDerivedType ()
756 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
758 string s = ser.Serialize (c);
759 C c2 = ser.Deserialize<C> (s);
760 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
761 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
765 public void SerializeContainedDerivedType2 ()
767 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
769 string s = ser.Serialize (c);
770 C c2 = (C)ser.DeserializeObject (s);
771 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
772 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
776 public void SerializeWithTypeConverter ()
778 JavaScriptSerializer ser = new JavaScriptSerializer ();
779 MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
780 string s = ser.Serialize (uri);
781 MyUri uri2 = ser.Deserialize<MyUri> (s);
782 Assert.AreEqual (uri, uri2);
786 public void SerializeWithTypeConverter2 ()
788 JavaScriptSerializer ser = new JavaScriptSerializer ();
789 MyPointContainer pc = new MyPointContainer(new Point(15, 16));
790 string s = ser.Serialize(pc);
791 MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
795 public void MaxJsonLengthDeserializeObject ()
797 JavaScriptSerializer ser = new JavaScriptSerializer ();
798 ser.MaxJsonLength = 16;
799 object o = ser.DeserializeObject ("{s:'1234567890'}");
803 [ExpectedException(typeof(ArgumentException))]
804 public void MaxJsonLengthDeserializeObjectToLong ()
806 JavaScriptSerializer ser = new JavaScriptSerializer ();
807 ser.MaxJsonLength = 15;
808 object o = ser.DeserializeObject ("{s:'1234567890'}");
812 public void MaxJsonLengthSerialize ()
814 JavaScriptSerializer ser = new JavaScriptSerializer ();
815 ser.MaxJsonLength = 9;
817 string s = ser.Serialize (y);
821 [ExpectedException (typeof (InvalidOperationException))]
822 public void MaxJsonLengthSerializeToLong ()
824 JavaScriptSerializer ser = new JavaScriptSerializer ();
825 ser.MaxJsonLength = 8;
827 string s = ser.Serialize (y);
831 public void RecursionLimitDeserialize1 ()
833 JavaScriptSerializer ser = new JavaScriptSerializer ();
834 ser.RecursionLimit = 3;
835 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
839 public void RecursionLimitDeserialize2 ()
841 JavaScriptSerializer ser = new JavaScriptSerializer ();
842 ser.RecursionLimit = 2;
843 YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
847 public void RecursionLimitDeserialize3 ()
849 JavaScriptSerializer ser = new JavaScriptSerializer ();
850 ser.RecursionLimit = 1;
851 object o = ser.DeserializeObject ("\"xxx\"");
855 [ExpectedException(typeof(ArgumentException))]
856 public void RecursionLimitDeserializeToDeap ()
858 JavaScriptSerializer ser = new JavaScriptSerializer ();
859 ser.RecursionLimit = 2;
860 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
864 public void RecursionLimitSerialize ()
866 JavaScriptSerializer ser = new JavaScriptSerializer ();
867 ser.RecursionLimit = 3;
869 string s = ser.Serialize (yy);
873 [ExpectedException(typeof(ArgumentException))]
874 public void RecursionLimitSerializeToDeap ()
876 JavaScriptSerializer ser = new JavaScriptSerializer ();
877 ser.RecursionLimit = 2;
879 string s = ser.Serialize (yy);
883 public void RecursionLimitSerialize2 ()
885 JavaScriptSerializer ser = new JavaScriptSerializer ();
886 ser.RecursionLimit = 2;
888 StringBuilder b = new StringBuilder ();
889 bool caughtException = false;
891 ser.Serialize (yy, b);
894 caughtException = true;
896 Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
897 Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
901 public void SimpleTypeResolver ()
903 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
905 string s = ser.Serialize (yy);
906 string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
908 Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
910 expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
911 Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
914 public class CustomResolver : JavaScriptTypeResolver
916 public CustomResolver ()
921 public override Type ResolveType (string id)
923 ResolvedIds.Add (id);
939 return typeof (long);
942 return typeof (string);
945 return typeof(Point);
950 public override string ResolveTypeId (Type type)
953 throw new ArgumentNullException ("type");
956 ResolvedTypes.Add (type.Name);
958 if (type == typeof (YY))
961 if (type == typeof (Y))
964 if (type == typeof (X))
967 if (type == typeof (int))
970 if (type == typeof (long))
973 if (type == typeof (string))
976 if (type == typeof(Point))
982 public static List<string> ResolvedTypes {
984 if (resolvedTypes == null) {
985 resolvedTypes = new List<string> ();
987 return resolvedTypes;
991 public static List<string> ResolvedIds {
993 if (resolvedIds == null) {
994 resolvedIds = new List<string> ();
1000 public static void Reset ()
1003 resolvedTypes = null;
1006 private static List<string> resolvedTypes;
1007 private static List<string> resolvedIds;
1011 public void CustomTypeResolver ()
1013 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
1017 string s = ser.Serialize (x);
1019 CustomResolver.Reset ();
1020 X x1 = (X) ser.DeserializeObject (s);
1021 Assert.IsTrue (x.Equals (x1), "x != x1");
1023 CustomResolver.Reset ();
1024 X x2 = ser.Deserialize<X> (s);
1025 Assert.IsTrue (x.Equals (x2), "x != x2");