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 MonoTests.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);
402 Assert.AreEqual ("{\"z\":8,\"ch\":\"v\",\"ch_null\":null,\"str\":\"vwF59g\",\"b\":253,\"sb\":-48,\"sh\":-32740,\"ush\":65511,\"i\":-234235453,\"ui\":4294733061,\"l\":-9223372036854775780,\"ul\":18446744073709551612,\"f\":NaN,\"f1\":-Infinity,\"f2\":Infinity,\"f3\":-3.40282347E+38,\"f4\":3.40282347E+38,\"d\":NaN,\"d1\":-Infinity,\"d2\":Infinity,\"d3\":-1.7976931348623157E+308,\"d4\":1.7976931348623157E+308,\"de\":-1,\"de1\":0,\"de2\":1,\"de3\":-79228162514264337593543950335,\"de4\":79228162514264337593543950335,\"g\":\"000000ea-0002-0162-0102-030405060708\",\"nb\":null,\"dbn\":null,\"uri\":\"http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d\",\"hash\":{\"mykey\":{\"BB\":10}},\"point\":{\"IsEmpty\":false,\"X\":150,\"Y\":150},\"MyEnum\":[1,10,345],\"MyEnum1\":[1,10,345],\"AA\":5,\"AA1\":[{\"BB\":10},{\"BB\":10}],\"BB\":18446744073709551610,\"YY\":[{\"BB\":10},{\"BB\":10}]}", x, "#A1");
404 X n = ser.Deserialize<X> (x);
405 Assert.AreEqual (s, n, "#A2");
407 //string json = "\\uFF56";
408 //string result = ser.Deserialize<string> (json);
409 //Assert.AreEqual ("\uFF56", result);
411 //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
415 public void TestDeserializeTypeResolver ()
417 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
421 string s = ser.Serialize (x);
422 Console.WriteLine (s);
423 Assert.AreEqual ("{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+X, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"z\":8,\"ch\":\"v\",\"ch_null\":null,\"str\":\"vwF59g\",\"b\":253,\"sb\":-48,\"sh\":-32740,\"ush\":65511,\"i\":-234235453,\"ui\":4294733061,\"l\":-9223372036854775780,\"ul\":18446744073709551612,\"f\":NaN,\"f1\":-Infinity,\"f2\":Infinity,\"f3\":-3.40282347E+38,\"f4\":3.40282347E+38,\"d\":NaN,\"d1\":-Infinity,\"d2\":Infinity,\"d3\":-1.7976931348623157E+308,\"d4\":1.7976931348623157E+308,\"de\":-1,\"de1\":0,\"de2\":1,\"de3\":-79228162514264337593543950335,\"de4\":79228162514264337593543950335,\"g\":\"000000ea-0002-0162-0102-030405060708\",\"nb\":null,\"dbn\":null,\"uri\":\"http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d\",\"hash\":{\"mykey\":{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}},\"point\":{\"__type\":\"System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\",\"IsEmpty\":false,\"X\":150,\"Y\":150},\"MyEnum\":[1,10,345],\"MyEnum1\":[1,10,345],\"AA\":5,\"AA1\":[{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10},{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}],\"BB\":18446744073709551610,\"YY\":[{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10},{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_2_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}]}", s, "#A1");
425 X x2 = ser.Deserialize<X> (s);
426 Assert.AreEqual (x, x2, "#A2");
430 public void TestDeserializeBugs () {
431 JavaScriptSerializer ser = new JavaScriptSerializer ();
435 string x = ser.Serialize (s);
436 bug n = ser.Deserialize<bug> (x);
437 Assert.AreEqual (s, n);
439 // Should check correctness with .Net GA:
440 //js = ser.Serialize (Color.Red);
441 //Color ccc = ser.Deserialize<Color> (js);
442 //string xml = @"<root><node attr=""xxx""/></root>";
444 //XmlDocument doc = new XmlDocument ();
446 //string js = ser.Serialize (doc);
447 //DataTable table = new DataTable();
448 //table.Columns.Add ("col1", typeof (int));
449 //table.Columns.Add ("col2", typeof (float));
450 //table.Rows.Add (1, 1f);
451 //table.Rows.Add (234234, 2.4f);
453 //string js = ser.Serialize (table);
456 static void FieldsEqual (object expected, object actual) {
457 Assert.AreEqual (expected.GetType (), actual.GetType ());
458 FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
459 foreach (FieldInfo info in infos) {
460 object value1 = info.GetValue (expected);
461 object value2 = info.GetValue (actual);
462 if (value1 is IEnumerable) {
463 IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
465 foreach (object x in (IEnumerable) value1) {
466 if (!yenum.MoveNext ())
467 Assert.Fail (info.Name + " index:" + index);
469 if (x is DictionaryEntry) {
470 DictionaryEntry entry = (DictionaryEntry)x;
471 IDictionary dict = (IDictionary) value2;
472 Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
475 Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
477 Assert.IsFalse (yenum.MoveNext (), info.Name);
480 Assert.AreEqual (value1, value2, info.Name);
486 [ExpectedException (typeof (ArgumentNullException))]
487 public void TestDeserialize1 () {
488 JavaScriptSerializer ser = new JavaScriptSerializer ();
489 ser.Deserialize<string> (null);
493 [ExpectedException (typeof (ArgumentNullException))]
494 public void TestDeserializeNullConverter () {
495 JavaScriptSerializer ser = new JavaScriptSerializer ();
496 ser.RegisterConverters (null);
500 public void TestDeserializeConverter () {
501 JavaScriptSerializer ser = new JavaScriptSerializer ();
502 List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
503 list.Add (new MyJavaScriptConverter ());
504 list.Add (new CultureInfoConverter ());
505 ser.RegisterConverters (list);
506 string result = ser.Serialize (new X [] { new X (), new X () });
507 Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
508 result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
512 public void TestDeserializeConverter1 () {
513 JavaScriptSerializer serializer = new JavaScriptSerializer ();
515 serializer.RegisterConverters (new JavaScriptConverter [] {new ListItemCollectionConverter()});
517 ListBox ListBox1 = new ListBox ();
518 ListBox1.Items.Add ("a1");
519 ListBox1.Items.Add ("a2");
520 ListBox1.Items.Add ("a3");
522 string x = serializer.Serialize (ListBox1.Items);
523 ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
524 Assert.AreEqual (3, recoveredList.Count);
528 public void TestSerialize1 () {
529 JavaScriptSerializer ser = new JavaScriptSerializer ();
530 Assert.AreEqual("null", ser.Serialize(null));
532 string js = ser.Serialize (1234);
533 Assert.AreEqual ("1234", js);
534 Assert.AreEqual (1234, ser.Deserialize<int> (js));
535 js = ser.Serialize (1.1);
536 Assert.AreEqual ("1.1", js);
537 Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
538 char [] chars = "faskjhfasd0981234".ToCharArray ();
539 js = ser.Serialize (chars);
540 char[] actual = ser.Deserialize<char[]> (js);
541 Assert.AreEqual (chars.Length, actual.Length);
542 for (int i = 0; i < chars.Length; i++)
543 Assert.AreEqual (chars[i], actual[i]);
545 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{|}~""";
546 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{|}~";
548 string serRes = ser.Serialize (data);
549 Assert.AreEqual (expected, serRes);
550 string deserRes = ser.Deserialize<string> (serRes);
551 Assert.AreEqual (data, deserRes);
555 [ExpectedException (typeof (ArgumentNullException))]
556 [Category ("NotDotNet")]
557 public void TestSerialize2 () {
558 JavaScriptSerializer ser = new JavaScriptSerializer ();
559 ser.Serialize ("aaa", (StringBuilder)null);
562 static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
565 public void TestSerializeDate () {
566 JavaScriptSerializer ser = new JavaScriptSerializer ();
567 DateTime now = new DateTime (633213894056010000L);
569 string actual = ser.Serialize (now);
570 DateTime dateTime = now.ToUniversalTime ();
571 long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
573 object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
574 Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
575 Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
579 public void TestSerializeEnum () {
580 JavaScriptSerializer ser = new JavaScriptSerializer ();
581 string result = ser.Serialize (MyEnum.BBB);
582 Assert.AreEqual ("1", result);
583 Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
586 class MyJavaScriptConverter : JavaScriptConverter
588 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
589 throw new Exception ("The method or operation is not implemented.");
592 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
593 Array a = (Array) obj;
594 Dictionary<string, object> d = new Dictionary<string, object> ();
598 //throw new Exception ("The method or operation is not implemented.");
601 public override IEnumerable<Type> SupportedTypes {
603 yield return typeof (X[]);
608 sealed class CultureInfoConverter : JavaScriptConverter
610 static readonly Type typeofCultureInfo = typeof (CultureInfo);
611 public override IEnumerable<Type> SupportedTypes {
612 get { yield return typeofCultureInfo; }
615 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
616 throw new NotSupportedException ();
619 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
620 CultureInfo ci = (CultureInfo)obj;
623 Dictionary<string, object> d = new Dictionary<string, object> ();
624 d.Add ("name", ci.Name);
625 d.Add ("numberFormat", ci.NumberFormat);
626 d.Add ("dateTimeFormat", ci.DateTimeFormat);
631 public class ListItemCollectionConverter : JavaScriptConverter
633 public override IEnumerable<Type> SupportedTypes {
634 //Define the ListItemCollection as a supported type.
635 get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
638 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
639 ListItemCollection listType = obj as ListItemCollection;
641 if (listType != null) {
642 // Create the representation.
643 Dictionary<string, object> result = new Dictionary<string, object> ();
644 ArrayList itemsList = new ArrayList ();
645 foreach (ListItem item in listType) {
646 //Add each entry to the dictionary.
647 Dictionary<string, object> listDict = new Dictionary<string, object> ();
648 listDict.Add ("Value", item.Value);
649 listDict.Add ("Text", item.Text);
650 itemsList.Add (listDict);
652 result ["List"] = itemsList;
656 return new Dictionary<string, object> ();
659 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
660 if (dictionary == null)
661 throw new ArgumentNullException ("dictionary");
663 if (type == typeof (ListItemCollection)) {
664 // Create the instance to deserialize into.
665 ListItemCollection list = new ListItemCollection ();
667 // Deserialize the ListItemCollection's items.
668 ArrayList itemsList = (ArrayList) dictionary ["List"];
669 for (int i = 0; i < itemsList.Count; i++)
670 list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
679 public void DeserializeObject () {
680 object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
681 Assert.IsNotNull (o as Dictionary<string, object>, "type");
682 Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
683 Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
684 Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
685 object [] array = (object []) dictionary ["Array"];
686 Assert.AreEqual (true, (bool) array [0], "array [0]");
687 Assert.AreEqual (false, (bool) array [1], "array [1]");
688 Assert.AreEqual (0, (int) array [2], "array [2]");
692 public void DeserializeObject2 ()
694 JavaScriptSerializer ser = new JavaScriptSerializer ();
696 string s = ser.Serialize (y);
697 object y2 = ser.DeserializeObject (s);
698 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
702 public void DeserializeObject3 ()
704 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
706 string s = ser.Serialize (y);
707 object y2 = ser.DeserializeObject (s);
708 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
712 public void DeserializeObject4 ()
714 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
716 string s = ser.Serialize (y);
717 object y2 = ser.DeserializeObject (s);
718 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
719 Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
720 Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
721 Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
722 Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
726 [ExpectedException(typeof(ArgumentNullException))]
727 public void SerializeWithResolverDeserializeWithout ()
729 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
731 string s = ser.Serialize (y);
732 ser = new JavaScriptSerializer ();
733 object y2 = ser.DeserializeObject (s);
737 public void SerializeWithoutResolverDeserializeWith ()
739 JavaScriptSerializer ser = new JavaScriptSerializer ();
741 string s = ser.Serialize (y);
742 ser = new JavaScriptSerializer (new SimpleTypeResolver ());
743 object y2 = ser.DeserializeObject (s);
744 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
750 public string s1 = "s1";
756 public string s2 = "s2";
761 public B b1 = new B ();
762 public B b2 = new D ();
766 public void SerializeDerivedType ()
768 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
770 string s = ser.Serialize (b);
771 B b2 = ser.Deserialize<B> (s);
772 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
776 public void SerializeDerivedType2 ()
778 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
780 string s = ser.Serialize (b);
781 B b2 = (B)ser.DeserializeObject (s);
782 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
786 public void SerializeContainedDerivedType ()
788 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
790 string s = ser.Serialize (c);
791 C c2 = ser.Deserialize<C> (s);
792 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
793 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
797 public void SerializeContainedDerivedType2 ()
799 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
801 string s = ser.Serialize (c);
802 C c2 = (C)ser.DeserializeObject (s);
803 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
804 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
808 public void SerializeWithTypeConverter ()
810 JavaScriptSerializer ser = new JavaScriptSerializer ();
811 MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
812 string s = ser.Serialize (uri);
813 MyUri uri2 = ser.Deserialize<MyUri> (s);
814 Assert.AreEqual (uri, uri2);
818 public void SerializeWithTypeConverter2 ()
820 JavaScriptSerializer ser = new JavaScriptSerializer ();
821 MyPointContainer pc = new MyPointContainer(new Point(15, 16));
822 string s = ser.Serialize(pc);
823 MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
827 public void MaxJsonLengthDeserializeObject ()
829 JavaScriptSerializer ser = new JavaScriptSerializer ();
830 ser.MaxJsonLength = 16;
831 object o = ser.DeserializeObject ("{s:'1234567890'}");
835 [ExpectedException(typeof(ArgumentException))]
836 public void MaxJsonLengthDeserializeObjectToLong ()
838 JavaScriptSerializer ser = new JavaScriptSerializer ();
839 ser.MaxJsonLength = 15;
840 object o = ser.DeserializeObject ("{s:'1234567890'}");
844 public void MaxJsonLengthSerialize ()
846 JavaScriptSerializer ser = new JavaScriptSerializer ();
847 ser.MaxJsonLength = 9;
849 string s = ser.Serialize (y);
853 [ExpectedException (typeof (InvalidOperationException))]
854 public void MaxJsonLengthSerializeToLong ()
856 JavaScriptSerializer ser = new JavaScriptSerializer ();
857 ser.MaxJsonLength = 8;
859 string s = ser.Serialize (y);
863 public void RecursionLimitDeserialize1 ()
865 JavaScriptSerializer ser = new JavaScriptSerializer ();
866 ser.RecursionLimit = 3;
867 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
871 public void RecursionLimitDeserialize2 ()
873 JavaScriptSerializer ser = new JavaScriptSerializer ();
874 ser.RecursionLimit = 2;
875 YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
879 public void RecursionLimitDeserialize3 ()
881 JavaScriptSerializer ser = new JavaScriptSerializer ();
882 ser.RecursionLimit = 1;
883 object o = ser.DeserializeObject ("\"xxx\"");
887 [ExpectedException(typeof(ArgumentException))]
888 public void RecursionLimitDeserializeToDeep ()
890 JavaScriptSerializer ser = new JavaScriptSerializer ();
891 ser.RecursionLimit = 2;
892 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
896 public void RecursionLimitSerialize ()
898 JavaScriptSerializer ser = new JavaScriptSerializer ();
899 ser.RecursionLimit = 3;
901 string s = ser.Serialize (yy);
905 [ExpectedException(typeof(ArgumentException))]
906 public void RecursionLimitSerializeToDeep ()
908 JavaScriptSerializer ser = new JavaScriptSerializer ();
909 ser.RecursionLimit = 2;
911 string s = ser.Serialize (yy);
915 public void RecursionLimitSerialize2 ()
917 JavaScriptSerializer ser = new JavaScriptSerializer ();
918 ser.RecursionLimit = 2;
920 StringBuilder b = new StringBuilder ();
921 bool caughtException = false;
923 ser.Serialize (yy, b);
926 caughtException = true;
928 Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
929 Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
933 public void SimpleTypeResolver ()
935 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
937 string s = ser.Serialize (yy);
938 string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
940 Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
942 expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
943 Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
946 public class CustomResolver : JavaScriptTypeResolver
948 public CustomResolver ()
953 public override Type ResolveType (string id)
955 ResolvedIds.Add (id);
971 return typeof (long);
974 return typeof (string);
977 return typeof(Point);
982 public override string ResolveTypeId (Type type)
985 throw new ArgumentNullException ("type");
988 ResolvedTypes.Add (type.Name);
990 if (type == typeof (YY))
993 if (type == typeof (Y))
996 if (type == typeof (X))
999 if (type == typeof (int))
1002 if (type == typeof (long))
1005 if (type == typeof (string))
1008 if (type == typeof(Point))
1014 public static List<string> ResolvedTypes {
1016 if (resolvedTypes == null) {
1017 resolvedTypes = new List<string> ();
1019 return resolvedTypes;
1023 public static List<string> ResolvedIds {
1025 if (resolvedIds == null) {
1026 resolvedIds = new List<string> ();
1032 public static void Reset ()
1035 resolvedTypes = null;
1038 private static List<string> resolvedTypes;
1039 private static List<string> resolvedIds;
1043 [NUnit.Framework.Category ("NotWorking")]
1044 public void CustomTypeResolver ()
1046 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
1050 string s = ser.Serialize (x);
1052 CustomResolver.Reset ();
1053 X x1 = (X) ser.DeserializeObject (s);
1054 Assert.IsTrue (x.Equals (x1), "x != x1");
1056 CustomResolver.Reset ();
1057 X x2 = ser.Deserialize<X> (s);
1058 Assert.IsTrue (x.Equals (x2), "x != x2");
1062 public void InfinityAndNaN ()
1064 JavaScriptSerializer ser = new JavaScriptSerializer ();
1066 double nan = Double.NaN;
1067 string s = ser.Serialize (nan);
1068 Assert.AreEqual (s, "NaN", "#A1");
1069 nan = (double)ser.DeserializeObject (s);
1070 Assert.AreEqual (Double.NaN, nan, "#A2");
1071 nan = (double)ser.Deserialize <double> (s);
1072 Assert.AreEqual (Double.NaN, nan, "#A3");
1074 double infinity = Double.PositiveInfinity;
1075 s = ser.Serialize (infinity);
1076 Assert.AreEqual (s, "Infinity", "#B1");
1077 infinity = (double)ser.DeserializeObject (s);
1078 Assert.AreEqual (Double.PositiveInfinity, infinity, "#B2");
1079 infinity = ser.Deserialize <double> (s);
1080 Assert.AreEqual (Double.PositiveInfinity, infinity, "#B3");
1082 infinity = Double.NegativeInfinity;
1083 s = ser.Serialize (infinity);
1084 Assert.AreEqual (s, "-Infinity", "#C1");
1085 infinity = (double)ser.DeserializeObject (s);
1086 Assert.AreEqual (Double.NegativeInfinity, infinity, "#C2");
1087 infinity = ser.Deserialize <double> (s);
1088 Assert.AreEqual (Double.NegativeInfinity, infinity, "#C3");
1090 var dict = new Dictionary <string, object> ();
1091 dict.Add ("A", Double.NaN);
1092 dict.Add ("B", Double.PositiveInfinity);
1093 dict.Add ("C", Double.NegativeInfinity);
1094 s = ser.Serialize (dict);
1095 Assert.AreEqual ("{\"A\":NaN,\"B\":Infinity,\"C\":-Infinity}", s, "#D1");
1097 dict = (Dictionary <string, object>)ser.DeserializeObject (s);
1098 Assert.AreEqual (Double.NaN, dict ["A"], "#D2");
1099 Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D3");
1100 Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D4");
1102 dict = (Dictionary <string, object>)ser.Deserialize <Dictionary <string, object>> (s);
1103 Assert.AreEqual (Double.NaN, dict ["A"], "#D5");
1104 Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D6");
1105 Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D7");
1107 var arr = new ArrayList () {
1109 Double.PositiveInfinity,
1110 Double.NegativeInfinity};
1111 s = ser.Serialize (arr);
1112 Assert.AreEqual ("[NaN,Infinity,-Infinity]", s, "#E1");
1114 object[] arr2 = (object[])ser.DeserializeObject (s);
1115 Assert.AreEqual (3, arr2.Length, "#E2");
1116 Assert.AreEqual (Double.NaN, arr2 [0], "#E3");
1117 Assert.AreEqual (Double.PositiveInfinity, arr2 [1], "#E4");
1118 Assert.AreEqual (Double.NegativeInfinity, arr2 [2], "#E5");
1120 arr = ser.Deserialize <ArrayList> (s);
1121 Assert.AreEqual (3, arr.Count, "#E6");
1122 Assert.AreEqual (Double.NaN, arr [0], "#E7");
1123 Assert.AreEqual (Double.PositiveInfinity, arr [1], "#E8");
1124 Assert.AreEqual (Double.NegativeInfinity, arr [2], "#E9");
1128 public void StandalonePrimitives ()
1130 JavaScriptSerializer ser = new JavaScriptSerializer ();
1135 o = ser.DeserializeObject ("1");
1136 Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A1");
1138 Assert.AreEqual (1, i, "#A2");
1139 o =ser.DeserializeObject ("-1");
1140 Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A3");
1142 Assert.AreEqual (-1, i, "#A4");
1144 o = ser.DeserializeObject ("2147483649");
1145 Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B1");
1147 Assert.AreEqual (2147483649, l, "#B2");
1148 o = ser.DeserializeObject ("-2147483649");
1149 Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B3");
1151 Assert.AreEqual (-2147483649, l, "#B4");
1153 o = ser.DeserializeObject ("9223372036854775808");
1154 Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C1");
1155 decimal d = (decimal)o;
1156 Assert.AreEqual (9223372036854775808m, d, "#C2");
1157 o = ser.DeserializeObject ("-9223372036854775809");
1158 Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C3");
1160 Assert.AreEqual (-9223372036854775809m, d, "#C4");
1162 o = ser.DeserializeObject ("79228162514264337593543950336");
1163 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D1");
1164 double db = (double)o;
1165 Assert.AreEqual (79228162514264337593543950336.0, db, "#D2");
1166 o = ser.DeserializeObject ("-79228162514264337593543950336");
1167 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D3");
1169 Assert.AreEqual (-79228162514264337593543950336.0, db, "#D4");
1171 o = ser.DeserializeObject ("\"test string\"");
1172 Assert.AreEqual (typeof (global::System.String), o.GetType (), "#E1");
1173 string s = (string)o;
1174 Assert.AreEqual ("test string", s, "#E2");
1176 o = ser.DeserializeObject ("true");
1177 Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F1");
1179 Assert.AreEqual (true, b, "#F2");
1181 o = ser.DeserializeObject ("false");
1182 Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F3");
1184 Assert.AreEqual (false, b, "#F4");
1186 o = ser.DeserializeObject ("-1.7976931348623157E+308");
1187 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G1");
1189 Assert.AreEqual (Double.MinValue, db, "#G2");
1191 o = ser.DeserializeObject ("1.7976931348623157E+308");
1192 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G3");
1194 Assert.AreEqual (Double.MaxValue, db, "#G4");
1197 class SomeDict : IDictionary<string, object>
1199 void IDictionary<string, object>.Add (string key, object value) {
1200 throw new NotSupportedException ();
1203 bool IDictionary<string, object>.ContainsKey (string key) {
1204 throw new NotSupportedException ();
1207 ICollection<string> IDictionary<string, object>.Keys {
1208 get { throw new NotSupportedException (); }
1211 bool IDictionary<string, object>.Remove (string key) {
1212 throw new NotSupportedException ();
1215 bool IDictionary<string, object>.TryGetValue (string key, out object value) {
1216 throw new NotSupportedException ();
1219 ICollection<object> IDictionary<string, object>.Values {
1220 get { throw new NotSupportedException (); }
1223 object IDictionary<string, object>.this [string key] {
1224 get { throw new NotSupportedException (); }
1225 set { throw new NotSupportedException (); }
1228 void ICollection<KeyValuePair<string, object>>.Add (KeyValuePair<string, object> item) {
1229 throw new NotSupportedException ();
1232 void ICollection<KeyValuePair<string, object>>.Clear () {
1233 throw new NotSupportedException ();
1236 bool ICollection<KeyValuePair<string, object>>.Contains (KeyValuePair<string, object> item) {
1237 throw new NotSupportedException ();
1240 void ICollection<KeyValuePair<string, object>>.CopyTo (KeyValuePair<string, object> [] array, int arrayIndex) {
1241 throw new NotSupportedException ();
1244 int ICollection<KeyValuePair<string, object>>.Count {
1245 get { throw new NotSupportedException (); }
1248 bool ICollection<KeyValuePair<string, object>>.IsReadOnly {
1249 get { throw new NotSupportedException (); }
1252 bool ICollection<KeyValuePair<string, object>>.Remove (KeyValuePair<string, object> item) {
1253 throw new NotSupportedException ();
1256 IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator () {
1257 return GetEnumerator ();
1260 IEnumerator IEnumerable.GetEnumerator () {
1261 return ((IEnumerable<KeyValuePair<string, object>>) this).GetEnumerator ();
1264 protected IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
1265 yield return new KeyValuePair<string, object> ("hello", "world");
1269 [Test] //bug #424704
1270 public void NonGenericClassImplementingClosedGenericIDictionary ()
1272 JavaScriptSerializer ser = new JavaScriptSerializer ();
1274 SomeDict dictIn = new SomeDict ();
1276 string s = ser.Serialize (dictIn);
1278 Dictionary<string, object> dictOut = ser.Deserialize<Dictionary<string, object>> (s);
1279 Assert.AreEqual (dictOut.Count, 1, "#1");
1280 Assert.AreEqual (dictOut["hello"], "world", "#2");
1284 public void ConvertToIDictionary ()
1286 JavaScriptSerializer jss = new JavaScriptSerializer ();
1287 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}}";
1288 object input = jss.Deserialize<IDictionary>(json);
1289 IDictionary o = jss.ConvertToType<IDictionary>(input);
1291 Assert.IsTrue (o != null, "#A1");
1292 Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1296 public void ConvertToGenericIDictionary ()
1298 JavaScriptSerializer jss = new JavaScriptSerializer ();
1299 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}}";
1301 object input = jss.Deserialize<IDictionary>(json);
1303 IDictionary <string, object> o = jss.ConvertToType<IDictionary <string, object>>(input);
1304 Assert.IsTrue (o != null, "#A1");
1305 Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1307 IDictionary <object, object> o1 = jss.ConvertToType<IDictionary <object, object>>(input);
1308 Assert.IsTrue (o1 != null, "#B1");
1309 Assert.AreEqual (typeof (Dictionary <object, object>), o1.GetType (), "#B2");
1313 [ExpectedException (typeof (InvalidOperationException))]
1314 public void ConvertToGenericIDictionary_InvalidDefinition ()
1316 JavaScriptSerializer jss = new JavaScriptSerializer ();
1317 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}}";
1319 object input = jss.Deserialize<IDictionary>(json);
1320 IDictionary <int, object> o = jss.ConvertToType<IDictionary <int, object>>(input);