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 TestDeserializeUnquotedKeys ()
368 JavaScriptSerializer ser = new JavaScriptSerializer ();
369 IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:\"1\",itemTwo:\"2\"}");
371 Assert.AreEqual ("1", dict ["itemOne"], "#A1");
372 Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
374 dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:1,itemTwo:2}");
375 Assert.AreEqual (1, dict ["itemOne"], "#B1");
376 Assert.AreEqual (2, dict ["itemTwo"], "#B2");
380 public void TestDeserializeUnquotedKeysWithSpaces ()
382 JavaScriptSerializer ser = new JavaScriptSerializer ();
383 IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :\"1\",itemTwo:\"2\"}");
385 Assert.AreEqual ("1", dict ["itemOne"], "#A1");
386 Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
388 dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :1, itemTwo :2}");
389 Assert.AreEqual (1, dict ["itemOne"], "#B1");
390 Assert.AreEqual (2, dict ["itemTwo"], "#B2");
394 public void TestDeserialize () {
395 JavaScriptSerializer ser = new JavaScriptSerializer ();
396 Assert.IsNull (ser.Deserialize<X> (""));
400 string x = ser.Serialize (s);
401 X n = ser.Deserialize<X> (x);
402 Assert.AreEqual (s, n);
404 //string json = "\\uFF56";
405 //string result = ser.Deserialize<string> (json);
406 //Assert.AreEqual ("\uFF56", result);
408 //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
412 public void TestDeserializeTypeResolver ()
414 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
418 string s = ser.Serialize (x);
419 X x2 = ser.Deserialize<X> (s);
420 Assert.AreEqual (x, x2);
424 public void TestDeserializeBugs () {
425 JavaScriptSerializer ser = new JavaScriptSerializer ();
429 string x = ser.Serialize (s);
430 bug n = ser.Deserialize<bug> (x);
431 Assert.AreEqual (s, n);
433 // Should check correctness with .Net GA:
434 //js = ser.Serialize (Color.Red);
435 //Color ccc = ser.Deserialize<Color> (js);
436 //string xml = @"<root><node attr=""xxx""/></root>";
438 //XmlDocument doc = new XmlDocument ();
440 //string js = ser.Serialize (doc);
441 //DataTable table = new DataTable();
442 //table.Columns.Add ("col1", typeof (int));
443 //table.Columns.Add ("col2", typeof (float));
444 //table.Rows.Add (1, 1f);
445 //table.Rows.Add (234234, 2.4f);
447 //string js = ser.Serialize (table);
450 static void FieldsEqual (object expected, object actual) {
451 Assert.AreEqual (expected.GetType (), actual.GetType ());
452 FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
453 foreach (FieldInfo info in infos) {
454 object value1 = info.GetValue (expected);
455 object value2 = info.GetValue (actual);
456 if (value1 is IEnumerable) {
457 IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
459 foreach (object x in (IEnumerable) value1) {
460 if (!yenum.MoveNext ())
461 Assert.Fail (info.Name + " index:" + index);
463 if (x is DictionaryEntry) {
464 DictionaryEntry entry = (DictionaryEntry)x;
465 IDictionary dict = (IDictionary) value2;
466 Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
469 Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
471 Assert.IsFalse (yenum.MoveNext (), info.Name);
474 Assert.AreEqual (value1, value2, info.Name);
480 [ExpectedException (typeof (ArgumentNullException))]
481 public void TestDeserialize1 () {
482 JavaScriptSerializer ser = new JavaScriptSerializer ();
483 ser.Deserialize<string> (null);
487 [ExpectedException (typeof (ArgumentNullException))]
488 public void TestDeserializeNullConverter () {
489 JavaScriptSerializer ser = new JavaScriptSerializer ();
490 ser.RegisterConverters (null);
494 public void TestDeserializeConverter () {
495 JavaScriptSerializer ser = new JavaScriptSerializer ();
496 List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
497 list.Add (new MyJavaScriptConverter ());
498 list.Add (new CultureInfoConverter ());
499 ser.RegisterConverters (list);
500 string result = ser.Serialize (new X [] { new X (), new X () });
501 Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
502 result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
506 public void TestDeserializeConverter1 () {
507 JavaScriptSerializer serializer = new JavaScriptSerializer ();
509 serializer.RegisterConverters (new JavaScriptConverter [] {new ListItemCollectionConverter()});
511 ListBox ListBox1 = new ListBox ();
512 ListBox1.Items.Add ("a1");
513 ListBox1.Items.Add ("a2");
514 ListBox1.Items.Add ("a3");
516 string x = serializer.Serialize (ListBox1.Items);
517 ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
518 Assert.AreEqual (3, recoveredList.Count);
522 public void TestSerialize1 () {
523 JavaScriptSerializer ser = new JavaScriptSerializer ();
524 Assert.AreEqual("null", ser.Serialize(null));
526 string js = ser.Serialize (1234);
527 Assert.AreEqual ("1234", js);
528 Assert.AreEqual (1234, ser.Deserialize<int> (js));
529 js = ser.Serialize (1.1);
530 Assert.AreEqual ("1.1", js);
531 Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
532 char [] chars = "faskjhfasd0981234".ToCharArray ();
533 js = ser.Serialize (chars);
534 char[] actual = ser.Deserialize<char[]> (js);
535 Assert.AreEqual (chars.Length, actual.Length);
536 for (int i = 0; i < chars.Length; i++)
537 Assert.AreEqual (chars[i], actual[i]);
539 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{|}~""";
540 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{|}~";
542 string serRes = ser.Serialize (data);
543 Assert.AreEqual (expected, serRes);
544 string deserRes = ser.Deserialize<string> (serRes);
545 Assert.AreEqual (data, deserRes);
549 [ExpectedException (typeof (ArgumentNullException))]
550 [Category ("NotDotNet")]
551 public void TestSerialize2 () {
552 JavaScriptSerializer ser = new JavaScriptSerializer ();
553 ser.Serialize ("aaa", (StringBuilder)null);
556 static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
559 public void TestSerializeDate () {
560 JavaScriptSerializer ser = new JavaScriptSerializer ();
561 DateTime now = new DateTime (633213894056010000L);
563 string actual = ser.Serialize (now);
564 DateTime dateTime = now.ToUniversalTime ();
565 long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
567 object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
568 Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
569 Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
573 public void TestSerializeEnum () {
574 JavaScriptSerializer ser = new JavaScriptSerializer ();
575 string result = ser.Serialize (MyEnum.BBB);
576 Assert.AreEqual ("1", result);
577 Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
580 class MyJavaScriptConverter : JavaScriptConverter
582 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
583 throw new Exception ("The method or operation is not implemented.");
586 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
587 Array a = (Array) obj;
588 Dictionary<string, object> d = new Dictionary<string, object> ();
592 //throw new Exception ("The method or operation is not implemented.");
595 public override IEnumerable<Type> SupportedTypes {
597 yield return typeof (X[]);
602 sealed class CultureInfoConverter : JavaScriptConverter
604 static readonly Type typeofCultureInfo = typeof (CultureInfo);
605 public override IEnumerable<Type> SupportedTypes {
606 get { yield return typeofCultureInfo; }
609 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
610 throw new NotSupportedException ();
613 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
614 CultureInfo ci = (CultureInfo)obj;
617 Dictionary<string, object> d = new Dictionary<string, object> ();
618 d.Add ("name", ci.Name);
619 d.Add ("numberFormat", ci.NumberFormat);
620 d.Add ("dateTimeFormat", ci.DateTimeFormat);
625 public class ListItemCollectionConverter : JavaScriptConverter
627 public override IEnumerable<Type> SupportedTypes {
628 //Define the ListItemCollection as a supported type.
629 get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
632 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
633 ListItemCollection listType = obj as ListItemCollection;
635 if (listType != null) {
636 // Create the representation.
637 Dictionary<string, object> result = new Dictionary<string, object> ();
638 ArrayList itemsList = new ArrayList ();
639 foreach (ListItem item in listType) {
640 //Add each entry to the dictionary.
641 Dictionary<string, object> listDict = new Dictionary<string, object> ();
642 listDict.Add ("Value", item.Value);
643 listDict.Add ("Text", item.Text);
644 itemsList.Add (listDict);
646 result ["List"] = itemsList;
650 return new Dictionary<string, object> ();
653 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
654 if (dictionary == null)
655 throw new ArgumentNullException ("dictionary");
657 if (type == typeof (ListItemCollection)) {
658 // Create the instance to deserialize into.
659 ListItemCollection list = new ListItemCollection ();
661 // Deserialize the ListItemCollection's items.
662 ArrayList itemsList = (ArrayList) dictionary ["List"];
663 for (int i = 0; i < itemsList.Count; i++)
664 list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
673 public void DeserializeObject () {
674 object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
675 Assert.IsNotNull (o as Dictionary<string, object>, "type");
676 Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
677 Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
678 Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
679 object [] array = (object []) dictionary ["Array"];
680 Assert.AreEqual (true, (bool) array [0], "array [0]");
681 Assert.AreEqual (false, (bool) array [1], "array [1]");
682 Assert.AreEqual (0, (int) array [2], "array [2]");
686 public void DeserializeObject2 ()
688 JavaScriptSerializer ser = new JavaScriptSerializer ();
690 string s = ser.Serialize (y);
691 object y2 = ser.DeserializeObject (s);
692 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
696 public void DeserializeObject3 ()
698 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
700 string s = ser.Serialize (y);
701 object y2 = ser.DeserializeObject (s);
702 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
706 public void DeserializeObject4 ()
708 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
710 string s = ser.Serialize (y);
711 object y2 = ser.DeserializeObject (s);
712 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
713 Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
714 Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
715 Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
716 Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
720 [ExpectedException(typeof(ArgumentNullException))]
721 public void SerializeWithResolverDeserializeWithout ()
723 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
725 string s = ser.Serialize (y);
726 ser = new JavaScriptSerializer ();
727 object y2 = ser.DeserializeObject (s);
731 public void SerializeWithoutResolverDeserializeWith ()
733 JavaScriptSerializer ser = new JavaScriptSerializer ();
735 string s = ser.Serialize (y);
736 ser = new JavaScriptSerializer (new SimpleTypeResolver ());
737 object y2 = ser.DeserializeObject (s);
738 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
744 public string s1 = "s1";
750 public string s2 = "s2";
755 public B b1 = new B ();
756 public B b2 = new D ();
760 public void SerializeDerivedType ()
762 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
764 string s = ser.Serialize (b);
765 B b2 = ser.Deserialize<B> (s);
766 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
770 public void SerializeDerivedType2 ()
772 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
774 string s = ser.Serialize (b);
775 B b2 = (B)ser.DeserializeObject (s);
776 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
780 public void SerializeContainedDerivedType ()
782 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
784 string s = ser.Serialize (c);
785 C c2 = ser.Deserialize<C> (s);
786 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
787 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
791 public void SerializeContainedDerivedType2 ()
793 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
795 string s = ser.Serialize (c);
796 C c2 = (C)ser.DeserializeObject (s);
797 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
798 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
802 public void SerializeWithTypeConverter ()
804 JavaScriptSerializer ser = new JavaScriptSerializer ();
805 MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
806 string s = ser.Serialize (uri);
807 MyUri uri2 = ser.Deserialize<MyUri> (s);
808 Assert.AreEqual (uri, uri2);
812 public void SerializeWithTypeConverter2 ()
814 JavaScriptSerializer ser = new JavaScriptSerializer ();
815 MyPointContainer pc = new MyPointContainer(new Point(15, 16));
816 string s = ser.Serialize(pc);
817 MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
821 public void MaxJsonLengthDeserializeObject ()
823 JavaScriptSerializer ser = new JavaScriptSerializer ();
824 ser.MaxJsonLength = 16;
825 object o = ser.DeserializeObject ("{s:'1234567890'}");
829 [ExpectedException(typeof(ArgumentException))]
830 public void MaxJsonLengthDeserializeObjectToLong ()
832 JavaScriptSerializer ser = new JavaScriptSerializer ();
833 ser.MaxJsonLength = 15;
834 object o = ser.DeserializeObject ("{s:'1234567890'}");
838 public void MaxJsonLengthSerialize ()
840 JavaScriptSerializer ser = new JavaScriptSerializer ();
841 ser.MaxJsonLength = 9;
843 string s = ser.Serialize (y);
847 [ExpectedException (typeof (InvalidOperationException))]
848 public void MaxJsonLengthSerializeToLong ()
850 JavaScriptSerializer ser = new JavaScriptSerializer ();
851 ser.MaxJsonLength = 8;
853 string s = ser.Serialize (y);
857 public void RecursionLimitDeserialize1 ()
859 JavaScriptSerializer ser = new JavaScriptSerializer ();
860 ser.RecursionLimit = 3;
861 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
865 public void RecursionLimitDeserialize2 ()
867 JavaScriptSerializer ser = new JavaScriptSerializer ();
868 ser.RecursionLimit = 2;
869 YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
873 public void RecursionLimitDeserialize3 ()
875 JavaScriptSerializer ser = new JavaScriptSerializer ();
876 ser.RecursionLimit = 1;
877 object o = ser.DeserializeObject ("\"xxx\"");
881 [ExpectedException(typeof(ArgumentException))]
882 public void RecursionLimitDeserializeToDeep ()
884 JavaScriptSerializer ser = new JavaScriptSerializer ();
885 ser.RecursionLimit = 2;
886 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
890 public void RecursionLimitSerialize ()
892 JavaScriptSerializer ser = new JavaScriptSerializer ();
893 ser.RecursionLimit = 3;
895 string s = ser.Serialize (yy);
899 [ExpectedException(typeof(ArgumentException))]
900 public void RecursionLimitSerializeToDeep ()
902 JavaScriptSerializer ser = new JavaScriptSerializer ();
903 ser.RecursionLimit = 2;
905 string s = ser.Serialize (yy);
909 public void RecursionLimitSerialize2 ()
911 JavaScriptSerializer ser = new JavaScriptSerializer ();
912 ser.RecursionLimit = 2;
914 StringBuilder b = new StringBuilder ();
915 bool caughtException = false;
917 ser.Serialize (yy, b);
920 caughtException = true;
922 Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
923 Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
927 public void SimpleTypeResolver ()
929 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
931 string s = ser.Serialize (yy);
932 string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
934 Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
936 expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
937 Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
940 public class CustomResolver : JavaScriptTypeResolver
942 public CustomResolver ()
947 public override Type ResolveType (string id)
949 ResolvedIds.Add (id);
965 return typeof (long);
968 return typeof (string);
971 return typeof(Point);
976 public override string ResolveTypeId (Type type)
979 throw new ArgumentNullException ("type");
982 ResolvedTypes.Add (type.Name);
984 if (type == typeof (YY))
987 if (type == typeof (Y))
990 if (type == typeof (X))
993 if (type == typeof (int))
996 if (type == typeof (long))
999 if (type == typeof (string))
1002 if (type == typeof(Point))
1008 public static List<string> ResolvedTypes {
1010 if (resolvedTypes == null) {
1011 resolvedTypes = new List<string> ();
1013 return resolvedTypes;
1017 public static List<string> ResolvedIds {
1019 if (resolvedIds == null) {
1020 resolvedIds = new List<string> ();
1026 public static void Reset ()
1029 resolvedTypes = null;
1032 private static List<string> resolvedTypes;
1033 private static List<string> resolvedIds;
1037 [NUnit.Framework.Category ("NotWorking")]
1038 public void CustomTypeResolver ()
1040 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
1044 string s = ser.Serialize (x);
1046 CustomResolver.Reset ();
1047 X x1 = (X) ser.DeserializeObject (s);
1048 Assert.IsTrue (x.Equals (x1), "x != x1");
1050 CustomResolver.Reset ();
1051 X x2 = ser.Deserialize<X> (s);
1052 Assert.IsTrue (x.Equals (x2), "x != x2");
1056 public void InfinityAndNaN ()
1058 JavaScriptSerializer ser = new JavaScriptSerializer ();
1060 double nan = Double.NaN;
1061 string s = ser.Serialize (nan);
1062 Assert.AreEqual (s, "NaN", "#A1");
1063 nan = (double)ser.DeserializeObject (s);
1064 Assert.AreEqual (Double.NaN, nan, "#A2");
1065 nan = (double)ser.Deserialize <double> (s);
1066 Assert.AreEqual (Double.NaN, nan, "#A3");
1068 double infinity = Double.PositiveInfinity;
1069 s = ser.Serialize (infinity);
1070 Assert.AreEqual (s, "Infinity", "#B1");
1071 infinity = (double)ser.DeserializeObject (s);
1072 Assert.AreEqual (Double.PositiveInfinity, infinity, "#B2");
1073 infinity = ser.Deserialize <double> (s);
1074 Assert.AreEqual (Double.PositiveInfinity, infinity, "#B3");
1076 infinity = Double.NegativeInfinity;
1077 s = ser.Serialize (infinity);
1078 Assert.AreEqual (s, "-Infinity", "#C1");
1079 infinity = (double)ser.DeserializeObject (s);
1080 Assert.AreEqual (Double.NegativeInfinity, infinity, "#C2");
1081 infinity = ser.Deserialize <double> (s);
1082 Assert.AreEqual (Double.NegativeInfinity, infinity, "#C3");
1084 var dict = new Dictionary <string, object> ();
1085 dict.Add ("A", Double.NaN);
1086 dict.Add ("B", Double.PositiveInfinity);
1087 dict.Add ("C", Double.NegativeInfinity);
1088 s = ser.Serialize (dict);
1089 Assert.AreEqual ("{\"A\":NaN,\"B\":Infinity,\"C\":-Infinity}", s, "#D1");
1091 dict = (Dictionary <string, object>)ser.DeserializeObject (s);
1092 Assert.AreEqual (Double.NaN, dict ["A"], "#D2");
1093 Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D3");
1094 Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D4");
1096 dict = (Dictionary <string, object>)ser.Deserialize <Dictionary <string, object>> (s);
1097 Assert.AreEqual (Double.NaN, dict ["A"], "#D5");
1098 Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D6");
1099 Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D7");
1101 var arr = new ArrayList () {
1103 Double.PositiveInfinity,
1104 Double.NegativeInfinity};
1105 s = ser.Serialize (arr);
1106 Assert.AreEqual ("[NaN,Infinity,-Infinity]", s, "#E1");
1108 object[] arr2 = (object[])ser.DeserializeObject (s);
1109 Assert.AreEqual (3, arr2.Length, "#E2");
1110 Assert.AreEqual (Double.NaN, arr2 [0], "#E3");
1111 Assert.AreEqual (Double.PositiveInfinity, arr2 [1], "#E4");
1112 Assert.AreEqual (Double.NegativeInfinity, arr2 [2], "#E5");
1114 arr = ser.Deserialize <ArrayList> (s);
1115 Assert.AreEqual (3, arr.Count, "#E6");
1116 Assert.AreEqual (Double.NaN, arr [0], "#E7");
1117 Assert.AreEqual (Double.PositiveInfinity, arr [1], "#E8");
1118 Assert.AreEqual (Double.NegativeInfinity, arr [2], "#E9");
1122 public void StandalonePrimitives ()
1124 JavaScriptSerializer ser = new JavaScriptSerializer ();
1129 o = ser.DeserializeObject ("1");
1130 Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A1");
1132 Assert.AreEqual (1, i, "#A2");
1133 o =ser.DeserializeObject ("-1");
1134 Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A3");
1136 Assert.AreEqual (-1, i, "#A4");
1138 o = ser.DeserializeObject ("2147483649");
1139 Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B1");
1141 Assert.AreEqual (2147483649, l, "#B2");
1142 o = ser.DeserializeObject ("-2147483649");
1143 Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B3");
1145 Assert.AreEqual (-2147483649, l, "#B4");
1147 o = ser.DeserializeObject ("9223372036854775808");
1148 Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C1");
1149 decimal d = (decimal)o;
1150 Assert.AreEqual (9223372036854775808m, d, "#C2");
1151 o = ser.DeserializeObject ("-9223372036854775809");
1152 Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C3");
1154 Assert.AreEqual (-9223372036854775809m, d, "#C4");
1156 o = ser.DeserializeObject ("79228162514264337593543950336");
1157 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D1");
1158 double db = (double)o;
1159 Assert.AreEqual (79228162514264337593543950336.0, db, "#D2");
1160 o = ser.DeserializeObject ("-79228162514264337593543950336");
1161 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D3");
1163 Assert.AreEqual (-79228162514264337593543950336.0, db, "#D4");
1165 o = ser.DeserializeObject ("\"test string\"");
1166 Assert.AreEqual (typeof (global::System.String), o.GetType (), "#E1");
1167 string s = (string)o;
1168 Assert.AreEqual ("test string", s, "#E2");
1170 o = ser.DeserializeObject ("true");
1171 Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F1");
1173 Assert.AreEqual (true, b, "#F2");
1175 o = ser.DeserializeObject ("false");
1176 Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F3");
1178 Assert.AreEqual (false, b, "#F4");
1180 o = ser.DeserializeObject ("-1.7976931348623157E+308");
1181 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G1");
1183 Assert.AreEqual (Double.MinValue, db, "#G2");
1185 o = ser.DeserializeObject ("1.7976931348623157E+308");
1186 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G3");
1188 Assert.AreEqual (Double.MaxValue, db, "#G4");
1191 class SomeDict : IDictionary<string, object>
1193 void IDictionary<string, object>.Add (string key, object value) {
1194 throw new NotSupportedException ();
1197 bool IDictionary<string, object>.ContainsKey (string key) {
1198 throw new NotSupportedException ();
1201 ICollection<string> IDictionary<string, object>.Keys {
1202 get { throw new NotSupportedException (); }
1205 bool IDictionary<string, object>.Remove (string key) {
1206 throw new NotSupportedException ();
1209 bool IDictionary<string, object>.TryGetValue (string key, out object value) {
1210 throw new NotSupportedException ();
1213 ICollection<object> IDictionary<string, object>.Values {
1214 get { throw new NotSupportedException (); }
1217 object IDictionary<string, object>.this [string key] {
1218 get { throw new NotSupportedException (); }
1219 set { throw new NotSupportedException (); }
1222 void ICollection<KeyValuePair<string, object>>.Add (KeyValuePair<string, object> item) {
1223 throw new NotSupportedException ();
1226 void ICollection<KeyValuePair<string, object>>.Clear () {
1227 throw new NotSupportedException ();
1230 bool ICollection<KeyValuePair<string, object>>.Contains (KeyValuePair<string, object> item) {
1231 throw new NotSupportedException ();
1234 void ICollection<KeyValuePair<string, object>>.CopyTo (KeyValuePair<string, object> [] array, int arrayIndex) {
1235 throw new NotSupportedException ();
1238 int ICollection<KeyValuePair<string, object>>.Count {
1239 get { throw new NotSupportedException (); }
1242 bool ICollection<KeyValuePair<string, object>>.IsReadOnly {
1243 get { throw new NotSupportedException (); }
1246 bool ICollection<KeyValuePair<string, object>>.Remove (KeyValuePair<string, object> item) {
1247 throw new NotSupportedException ();
1250 IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator () {
1251 return GetEnumerator ();
1254 IEnumerator IEnumerable.GetEnumerator () {
1255 return ((IEnumerable<KeyValuePair<string, object>>) this).GetEnumerator ();
1258 protected IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
1259 yield return new KeyValuePair<string, object> ("hello", "world");
1263 [Test] //bug #424704
1264 public void NonGenericClassImplementingClosedGenericIDictionary ()
1266 JavaScriptSerializer ser = new JavaScriptSerializer ();
1268 SomeDict dictIn = new SomeDict ();
1270 string s = ser.Serialize (dictIn);
1272 Dictionary<string, object> dictOut = ser.Deserialize<Dictionary<string, object>> (s);
1273 Assert.AreEqual (dictOut.Count, 1, "#1");
1274 Assert.AreEqual (dictOut["hello"], "world", "#2");
1278 public void ConvertToIDictionary ()
1280 JavaScriptSerializer jss = new JavaScriptSerializer ();
1281 string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
1282 object input = jss.Deserialize<IDictionary>(json);
1283 IDictionary o = jss.ConvertToType<IDictionary>(input);
1285 Assert.IsTrue (o != null, "#A1");
1286 Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1290 public void ConvertToGenericIDictionary ()
1292 JavaScriptSerializer jss = new JavaScriptSerializer ();
1293 string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
1295 object input = jss.Deserialize<IDictionary>(json);
1297 IDictionary <string, object> o = jss.ConvertToType<IDictionary <string, object>>(input);
1298 Assert.IsTrue (o != null, "#A1");
1299 Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1301 IDictionary <object, object> o1 = jss.ConvertToType<IDictionary <object, object>>(input);
1302 Assert.IsTrue (o1 != null, "#B1");
1303 Assert.AreEqual (typeof (Dictionary <object, object>), o1.GetType (), "#B2");
1307 [ExpectedException (typeof (InvalidOperationException))]
1308 public void ConvertToGenericIDictionary_InvalidDefinition ()
1310 JavaScriptSerializer jss = new JavaScriptSerializer ();
1311 string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
1313 object input = jss.Deserialize<IDictionary>(json);
1314 IDictionary <int, object> o = jss.ConvertToType<IDictionary <int, object>>(input);