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 ();
351 Assert.AreEqual (2097152, ser.MaxJsonLength);
353 Assert.AreEqual (102400, ser.MaxJsonLength);
355 Assert.AreEqual (100, ser.RecursionLimit);
356 //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
357 //l.Add (new MyJavaScriptConverter ());
358 //ser.RegisterConverters (l);
359 //string x = ser.Serialize (new X [] { new X (), new X () });
360 //string s = ser.Serialize (new X());
361 //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
362 //X x = ser.Deserialize<X> (s);
363 //object ddd = typeof (Y).GetMember ("BB");
364 //object x1 = ser.Deserialize<X []> (null);
365 //object x2 = ser.Deserialize<X []> ("");
366 //object d = ser.Deserialize<X[]> (x);
370 public void TestDeserializeUnquotedKeys ()
372 JavaScriptSerializer ser = new JavaScriptSerializer ();
373 IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:\"1\",itemTwo:\"2\"}");
375 Assert.AreEqual ("1", dict ["itemOne"], "#A1");
376 Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
378 dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:1,itemTwo:2}");
379 Assert.AreEqual (1, dict ["itemOne"], "#B1");
380 Assert.AreEqual (2, dict ["itemTwo"], "#B2");
384 public void TestDeserializeUnquotedKeysWithSpaces ()
386 JavaScriptSerializer ser = new JavaScriptSerializer ();
387 IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :\"1\",itemTwo:\"2\"}");
389 Assert.AreEqual ("1", dict ["itemOne"], "#A1");
390 Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
392 dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :1, itemTwo :2}");
393 Assert.AreEqual (1, dict ["itemOne"], "#B1");
394 Assert.AreEqual (2, dict ["itemTwo"], "#B2");
398 public void TestDeserialize () {
399 JavaScriptSerializer ser = new JavaScriptSerializer ();
400 Assert.IsNull (ser.Deserialize<X> (""));
404 string x = ser.Serialize (s);
406 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");
408 X n = ser.Deserialize<X> (x);
409 Assert.AreEqual (s, n, "#A2");
411 //string json = "\\uFF56";
412 //string result = ser.Deserialize<string> (json);
413 //Assert.AreEqual ("\uFF56", result);
415 //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
419 public void TestDeserializeTypeResolver ()
422 string expected = "{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+X, System.Web.Extensions_test_net_4_5, 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_4_5, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}},\"point\":{\"__type\":\"System.Drawing.Point, System.Drawing, Version=4.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_4_5, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10},{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_4_5, 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_4_5, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10},{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, System.Web.Extensions_test_net_4_5, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}]}";
424 string expected = "{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+X, System.Web.Extensions_test_net_4_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_4_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}},\"point\":{\"__type\":\"System.Drawing.Point, System.Drawing, Version=4.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_4_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_4_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_4_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_4_0, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}]}";
426 string expected = "{\"__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}]}";
428 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
432 string s = ser.Serialize (x);
433 Assert.AreEqual (expected, s, "#A1");
435 X x2 = ser.Deserialize<X> (s);
436 Assert.AreEqual (x, x2, "#A2");
440 public void TestDeserializeBugs () {
441 JavaScriptSerializer ser = new JavaScriptSerializer ();
445 string x = ser.Serialize (s);
446 bug n = ser.Deserialize<bug> (x);
447 Assert.AreEqual (s, n);
449 // Should check correctness with .Net GA:
450 //js = ser.Serialize (Color.Red);
451 //Color ccc = ser.Deserialize<Color> (js);
452 //string xml = @"<root><node attr=""xxx""/></root>";
454 //XmlDocument doc = new XmlDocument ();
456 //string js = ser.Serialize (doc);
457 //DataTable table = new DataTable();
458 //table.Columns.Add ("col1", typeof (int));
459 //table.Columns.Add ("col2", typeof (float));
460 //table.Rows.Add (1, 1f);
461 //table.Rows.Add (234234, 2.4f);
463 //string js = ser.Serialize (table);
466 static void FieldsEqual (object expected, object actual) {
467 Assert.AreEqual (expected.GetType (), actual.GetType ());
468 FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
469 foreach (FieldInfo info in infos) {
470 object value1 = info.GetValue (expected);
471 object value2 = info.GetValue (actual);
472 if (value1 is IEnumerable) {
473 IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
475 foreach (object x in (IEnumerable) value1) {
476 if (!yenum.MoveNext ())
477 Assert.Fail (info.Name + " index:" + index);
479 if (x is DictionaryEntry) {
480 DictionaryEntry entry = (DictionaryEntry)x;
481 IDictionary dict = (IDictionary) value2;
482 Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
485 Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
487 Assert.IsFalse (yenum.MoveNext (), info.Name);
490 Assert.AreEqual (value1, value2, info.Name);
496 [ExpectedException (typeof (ArgumentNullException))]
497 public void TestDeserialize1 () {
498 JavaScriptSerializer ser = new JavaScriptSerializer ();
499 ser.Deserialize<string> (null);
503 [ExpectedException (typeof (ArgumentNullException))]
504 public void TestDeserializeNullConverter () {
505 JavaScriptSerializer ser = new JavaScriptSerializer ();
506 ser.RegisterConverters (null);
510 [SetCulture ("en-US")]
511 public void TestDeserializeConverter () {
512 JavaScriptSerializer ser = new JavaScriptSerializer ();
513 List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
514 list.Add (new MyJavaScriptConverter ());
515 list.Add (new CultureInfoConverter ());
516 ser.RegisterConverters (list);
517 string result = ser.Serialize (new X [] { new X (), new X () });
518 Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
519 result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
523 public void TestDeserializeConverter1 () {
524 JavaScriptSerializer serializer = new JavaScriptSerializer ();
526 serializer.RegisterConverters (new JavaScriptConverter [] {new ListItemCollectionConverter()});
528 ListBox ListBox1 = new ListBox ();
529 ListBox1.Items.Add ("a1");
530 ListBox1.Items.Add ("a2");
531 ListBox1.Items.Add ("a3");
533 string x = serializer.Serialize (ListBox1.Items);
534 ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
535 Assert.AreEqual (3, recoveredList.Count);
539 public void TestSerialize1 () {
540 JavaScriptSerializer ser = new JavaScriptSerializer ();
541 Assert.AreEqual("null", ser.Serialize(null));
543 string js = ser.Serialize (1234);
544 Assert.AreEqual ("1234", js);
545 Assert.AreEqual (1234, ser.Deserialize<int> (js));
546 js = ser.Serialize (1.1);
547 Assert.AreEqual ("1.1", js);
548 Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
549 char [] chars = "faskjhfasd0981234".ToCharArray ();
550 js = ser.Serialize (chars);
551 char[] actual = ser.Deserialize<char[]> (js);
552 Assert.AreEqual (chars.Length, actual.Length);
553 for (int i = 0; i < chars.Length; i++)
554 Assert.AreEqual (chars[i], actual[i]);
556 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{|}~""";
557 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{|}~";
559 string serRes = ser.Serialize (data);
560 Assert.AreEqual (expected, serRes);
561 string deserRes = ser.Deserialize<string> (serRes);
562 Assert.AreEqual (data, deserRes);
566 [ExpectedException (typeof (ArgumentNullException))]
567 [Category ("NotDotNet")]
568 public void TestSerialize2 () {
569 JavaScriptSerializer ser = new JavaScriptSerializer ();
570 ser.Serialize ("aaa", (StringBuilder)null);
573 static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
576 public void TestSerializeDate () {
577 JavaScriptSerializer ser = new JavaScriptSerializer ();
578 DateTime now = new DateTime (633213894056010000L);
580 string actual = ser.Serialize (now);
581 DateTime dateTime = now.ToUniversalTime ();
582 long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
584 object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
585 Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
586 Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
590 public void TestSerializeEnum () {
591 JavaScriptSerializer ser = new JavaScriptSerializer ();
592 string result = ser.Serialize (MyEnum.BBB);
593 Assert.AreEqual ("1", result);
594 Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
597 class MyJavaScriptConverter : JavaScriptConverter
599 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
600 throw new Exception ("The method or operation is not implemented.");
603 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
604 Array a = (Array) obj;
605 Dictionary<string, object> d = new Dictionary<string, object> ();
609 //throw new Exception ("The method or operation is not implemented.");
612 public override IEnumerable<Type> SupportedTypes {
614 yield return typeof (X[]);
619 sealed class CultureInfoConverter : JavaScriptConverter
621 static readonly Type typeofCultureInfo = typeof (CultureInfo);
622 public override IEnumerable<Type> SupportedTypes {
623 get { yield return typeofCultureInfo; }
626 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
627 throw new NotSupportedException ();
630 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
631 CultureInfo ci = (CultureInfo)obj;
634 Dictionary<string, object> d = new Dictionary<string, object> ();
635 d.Add ("name", ci.Name);
636 d.Add ("numberFormat", ci.NumberFormat);
637 d.Add ("dateTimeFormat", ci.DateTimeFormat);
642 public class ListItemCollectionConverter : JavaScriptConverter
644 public override IEnumerable<Type> SupportedTypes {
645 //Define the ListItemCollection as a supported type.
646 get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
649 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
650 ListItemCollection listType = obj as ListItemCollection;
652 if (listType != null) {
653 // Create the representation.
654 Dictionary<string, object> result = new Dictionary<string, object> ();
655 ArrayList itemsList = new ArrayList ();
656 foreach (ListItem item in listType) {
657 //Add each entry to the dictionary.
658 Dictionary<string, object> listDict = new Dictionary<string, object> ();
659 listDict.Add ("Value", item.Value);
660 listDict.Add ("Text", item.Text);
661 itemsList.Add (listDict);
663 result ["List"] = itemsList;
667 return new Dictionary<string, object> ();
670 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
671 if (dictionary == null)
672 throw new ArgumentNullException ("dictionary");
674 if (type == typeof (ListItemCollection)) {
675 // Create the instance to deserialize into.
676 ListItemCollection list = new ListItemCollection ();
678 // Deserialize the ListItemCollection's items.
679 ArrayList itemsList = (ArrayList) dictionary ["List"];
680 for (int i = 0; i < itemsList.Count; i++)
681 list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
690 public void DeserializeObject () {
691 object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
692 Assert.IsNotNull (o as Dictionary<string, object>, "type");
693 Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
694 Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
695 Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
696 object [] array = (object []) dictionary ["Array"];
697 Assert.AreEqual (true, (bool) array [0], "array [0]");
698 Assert.AreEqual (false, (bool) array [1], "array [1]");
699 Assert.AreEqual (0, (int) array [2], "array [2]");
703 public void DeserializeObject2 ()
705 JavaScriptSerializer ser = new JavaScriptSerializer ();
707 string s = ser.Serialize (y);
708 object y2 = ser.DeserializeObject (s);
709 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
713 public void DeserializeObject3 ()
715 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
717 string s = ser.Serialize (y);
718 object y2 = ser.DeserializeObject (s);
719 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
723 public void DeserializeObject4 ()
725 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
727 string s = ser.Serialize (y);
728 object y2 = ser.DeserializeObject (s);
729 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
730 Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
731 Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
732 Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
733 Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
737 [ExpectedException(typeof(ArgumentNullException))]
738 public void SerializeWithResolverDeserializeWithout ()
740 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
742 string s = ser.Serialize (y);
743 ser = new JavaScriptSerializer ();
744 object y2 = ser.DeserializeObject (s);
748 public void SerializeWithoutResolverDeserializeWith ()
750 JavaScriptSerializer ser = new JavaScriptSerializer ();
752 string s = ser.Serialize (y);
753 ser = new JavaScriptSerializer (new SimpleTypeResolver ());
754 object y2 = ser.DeserializeObject (s);
755 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
761 public string s1 = "s1";
767 public string s2 = "s2";
772 public B b1 = new B ();
773 public B b2 = new D ();
777 public void SerializeDerivedType ()
779 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
781 string s = ser.Serialize (b);
782 B b2 = ser.Deserialize<B> (s);
783 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
787 public void SerializeDerivedType2 ()
789 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
791 string s = ser.Serialize (b);
792 B b2 = (B)ser.DeserializeObject (s);
793 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
797 public void SerializeContainedDerivedType ()
799 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
801 string s = ser.Serialize (c);
802 C c2 = ser.Deserialize<C> (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 SerializeContainedDerivedType2 ()
810 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
812 string s = ser.Serialize (c);
813 C c2 = (C)ser.DeserializeObject (s);
814 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
815 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
819 public void SerializeWithTypeConverter ()
821 JavaScriptSerializer ser = new JavaScriptSerializer ();
822 MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
823 string s = ser.Serialize (uri);
824 MyUri uri2 = ser.Deserialize<MyUri> (s);
825 Assert.AreEqual (uri, uri2);
829 public void SerializeWithTypeConverter2 ()
831 JavaScriptSerializer ser = new JavaScriptSerializer ();
832 MyPointContainer pc = new MyPointContainer(new Point(15, 16));
833 string s = ser.Serialize(pc);
834 MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
838 public void MaxJsonLengthDeserializeObject ()
840 JavaScriptSerializer ser = new JavaScriptSerializer ();
841 ser.MaxJsonLength = 16;
842 object o = ser.DeserializeObject ("{s:'1234567890'}");
846 [ExpectedException(typeof(ArgumentException))]
847 public void MaxJsonLengthDeserializeObjectToLong ()
849 JavaScriptSerializer ser = new JavaScriptSerializer ();
850 ser.MaxJsonLength = 15;
851 object o = ser.DeserializeObject ("{s:'1234567890'}");
855 public void MaxJsonLengthSerialize ()
857 JavaScriptSerializer ser = new JavaScriptSerializer ();
858 ser.MaxJsonLength = 9;
860 string s = ser.Serialize (y);
864 [ExpectedException (typeof (InvalidOperationException))]
865 public void MaxJsonLengthSerializeToLong ()
867 JavaScriptSerializer ser = new JavaScriptSerializer ();
868 ser.MaxJsonLength = 8;
870 string s = ser.Serialize (y);
874 public void RecursionLimitDeserialize1 ()
876 JavaScriptSerializer ser = new JavaScriptSerializer ();
877 ser.RecursionLimit = 3;
878 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
882 public void RecursionLimitDeserialize2 ()
884 JavaScriptSerializer ser = new JavaScriptSerializer ();
885 ser.RecursionLimit = 2;
886 YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
890 public void RecursionLimitDeserialize3 ()
892 JavaScriptSerializer ser = new JavaScriptSerializer ();
893 ser.RecursionLimit = 1;
894 object o = ser.DeserializeObject ("\"xxx\"");
898 [ExpectedException(typeof(ArgumentException))]
899 public void RecursionLimitDeserializeToDeep ()
901 JavaScriptSerializer ser = new JavaScriptSerializer ();
902 ser.RecursionLimit = 2;
903 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
907 public void RecursionLimitSerialize ()
909 JavaScriptSerializer ser = new JavaScriptSerializer ();
910 ser.RecursionLimit = 3;
912 string s = ser.Serialize (yy);
916 [ExpectedException(typeof(ArgumentException))]
917 public void RecursionLimitSerializeToDeep ()
919 JavaScriptSerializer ser = new JavaScriptSerializer ();
920 ser.RecursionLimit = 2;
922 string s = ser.Serialize (yy);
926 public void RecursionLimitSerialize2 ()
928 JavaScriptSerializer ser = new JavaScriptSerializer ();
929 ser.RecursionLimit = 2;
931 StringBuilder b = new StringBuilder ();
932 bool caughtException = false;
934 ser.Serialize (yy, b);
937 caughtException = true;
939 Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
940 Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
944 public void SimpleTypeResolver ()
946 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
948 string s = ser.Serialize (yy);
949 string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
951 Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
953 expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
954 Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
957 public class CustomResolver : JavaScriptTypeResolver
959 public CustomResolver ()
964 public override Type ResolveType (string id)
966 ResolvedIds.Add (id);
982 return typeof (long);
985 return typeof (string);
988 return typeof(Point);
993 public override string ResolveTypeId (Type type)
996 throw new ArgumentNullException ("type");
999 ResolvedTypes.Add (type.Name);
1001 if (type == typeof (YY))
1004 if (type == typeof (Y))
1007 if (type == typeof (X))
1010 if (type == typeof (int))
1013 if (type == typeof (long))
1016 if (type == typeof (string))
1019 if (type == typeof(Point))
1025 public static List<string> ResolvedTypes {
1027 if (resolvedTypes == null) {
1028 resolvedTypes = new List<string> ();
1030 return resolvedTypes;
1034 public static List<string> ResolvedIds {
1036 if (resolvedIds == null) {
1037 resolvedIds = new List<string> ();
1043 public static void Reset ()
1046 resolvedTypes = null;
1049 private static List<string> resolvedTypes;
1050 private static List<string> resolvedIds;
1054 [NUnit.Framework.Category ("NotWorking")]
1055 public void CustomTypeResolver ()
1057 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
1061 string s = ser.Serialize (x);
1063 CustomResolver.Reset ();
1064 X x1 = (X) ser.DeserializeObject (s);
1065 Assert.IsTrue (x.Equals (x1), "x != x1");
1067 CustomResolver.Reset ();
1068 X x2 = ser.Deserialize<X> (s);
1069 Assert.IsTrue (x.Equals (x2), "x != x2");
1073 public void InfinityAndNaN ()
1075 JavaScriptSerializer ser = new JavaScriptSerializer ();
1077 double nan = Double.NaN;
1078 string s = ser.Serialize (nan);
1079 Assert.AreEqual (s, "NaN", "#A1");
1080 nan = (double)ser.DeserializeObject (s);
1081 Assert.AreEqual (Double.NaN, nan, "#A2");
1082 nan = (double)ser.Deserialize <double> (s);
1083 Assert.AreEqual (Double.NaN, nan, "#A3");
1085 double infinity = Double.PositiveInfinity;
1086 s = ser.Serialize (infinity);
1087 Assert.AreEqual (s, "Infinity", "#B1");
1088 infinity = (double)ser.DeserializeObject (s);
1089 Assert.AreEqual (Double.PositiveInfinity, infinity, "#B2");
1090 infinity = ser.Deserialize <double> (s);
1091 Assert.AreEqual (Double.PositiveInfinity, infinity, "#B3");
1093 infinity = Double.NegativeInfinity;
1094 s = ser.Serialize (infinity);
1095 Assert.AreEqual (s, "-Infinity", "#C1");
1096 infinity = (double)ser.DeserializeObject (s);
1097 Assert.AreEqual (Double.NegativeInfinity, infinity, "#C2");
1098 infinity = ser.Deserialize <double> (s);
1099 Assert.AreEqual (Double.NegativeInfinity, infinity, "#C3");
1101 var dict = new Dictionary <string, object> ();
1102 dict.Add ("A", Double.NaN);
1103 dict.Add ("B", Double.PositiveInfinity);
1104 dict.Add ("C", Double.NegativeInfinity);
1105 s = ser.Serialize (dict);
1106 Assert.AreEqual ("{\"A\":NaN,\"B\":Infinity,\"C\":-Infinity}", s, "#D1");
1108 dict = (Dictionary <string, object>)ser.DeserializeObject (s);
1109 Assert.AreEqual (Double.NaN, dict ["A"], "#D2");
1110 Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D3");
1111 Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D4");
1113 dict = (Dictionary <string, object>)ser.Deserialize <Dictionary <string, object>> (s);
1114 Assert.AreEqual (Double.NaN, dict ["A"], "#D5");
1115 Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D6");
1116 Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D7");
1118 var arr = new ArrayList () {
1120 Double.PositiveInfinity,
1121 Double.NegativeInfinity};
1122 s = ser.Serialize (arr);
1123 Assert.AreEqual ("[NaN,Infinity,-Infinity]", s, "#E1");
1125 object[] arr2 = (object[])ser.DeserializeObject (s);
1126 Assert.AreEqual (3, arr2.Length, "#E2");
1127 Assert.AreEqual (Double.NaN, arr2 [0], "#E3");
1128 Assert.AreEqual (Double.PositiveInfinity, arr2 [1], "#E4");
1129 Assert.AreEqual (Double.NegativeInfinity, arr2 [2], "#E5");
1131 arr = ser.Deserialize <ArrayList> (s);
1132 Assert.AreEqual (3, arr.Count, "#E6");
1133 Assert.AreEqual (Double.NaN, arr [0], "#E7");
1134 Assert.AreEqual (Double.PositiveInfinity, arr [1], "#E8");
1135 Assert.AreEqual (Double.NegativeInfinity, arr [2], "#E9");
1139 public void StandalonePrimitives ()
1141 JavaScriptSerializer ser = new JavaScriptSerializer ();
1146 o = ser.DeserializeObject ("1");
1147 Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A1");
1149 Assert.AreEqual (1, i, "#A2");
1150 o =ser.DeserializeObject ("-1");
1151 Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A3");
1153 Assert.AreEqual (-1, i, "#A4");
1155 o = ser.DeserializeObject ("2147483649");
1156 Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B1");
1158 Assert.AreEqual (2147483649, l, "#B2");
1159 o = ser.DeserializeObject ("-2147483649");
1160 Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B3");
1162 Assert.AreEqual (-2147483649, l, "#B4");
1164 o = ser.DeserializeObject ("9223372036854775808");
1165 Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C1");
1166 decimal d = (decimal)o;
1167 Assert.AreEqual (9223372036854775808m, d, "#C2");
1168 o = ser.DeserializeObject ("-9223372036854775809");
1169 Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C3");
1171 Assert.AreEqual (-9223372036854775809m, d, "#C4");
1173 o = ser.DeserializeObject ("79228162514264337593543950336");
1174 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D1");
1175 double db = (double)o;
1176 Assert.AreEqual (79228162514264337593543950336.0, db, "#D2");
1177 o = ser.DeserializeObject ("-79228162514264337593543950336");
1178 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D3");
1180 Assert.AreEqual (-79228162514264337593543950336.0, db, "#D4");
1182 o = ser.DeserializeObject ("\"test string\"");
1183 Assert.AreEqual (typeof (global::System.String), o.GetType (), "#E1");
1184 string s = (string)o;
1185 Assert.AreEqual ("test string", s, "#E2");
1187 o = ser.DeserializeObject ("true");
1188 Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F1");
1190 Assert.AreEqual (true, b, "#F2");
1192 o = ser.DeserializeObject ("false");
1193 Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F3");
1195 Assert.AreEqual (false, b, "#F4");
1197 o = ser.DeserializeObject ("-1.7976931348623157E+308");
1198 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G1");
1200 Assert.AreEqual (Double.MinValue, db, "#G2");
1202 o = ser.DeserializeObject ("1.7976931348623157E+308");
1203 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G3");
1205 Assert.AreEqual (Double.MaxValue, db, "#G4");
1208 class SomeDict : IDictionary<string, object>
1210 void IDictionary<string, object>.Add (string key, object value) {
1211 throw new NotSupportedException ();
1214 bool IDictionary<string, object>.ContainsKey (string key) {
1215 throw new NotSupportedException ();
1218 ICollection<string> IDictionary<string, object>.Keys {
1219 get { throw new NotSupportedException (); }
1222 bool IDictionary<string, object>.Remove (string key) {
1223 throw new NotSupportedException ();
1226 bool IDictionary<string, object>.TryGetValue (string key, out object value) {
1227 throw new NotSupportedException ();
1230 ICollection<object> IDictionary<string, object>.Values {
1231 get { throw new NotSupportedException (); }
1234 object IDictionary<string, object>.this [string key] {
1235 get { throw new NotSupportedException (); }
1236 set { throw new NotSupportedException (); }
1239 void ICollection<KeyValuePair<string, object>>.Add (KeyValuePair<string, object> item) {
1240 throw new NotSupportedException ();
1243 void ICollection<KeyValuePair<string, object>>.Clear () {
1244 throw new NotSupportedException ();
1247 bool ICollection<KeyValuePair<string, object>>.Contains (KeyValuePair<string, object> item) {
1248 throw new NotSupportedException ();
1251 void ICollection<KeyValuePair<string, object>>.CopyTo (KeyValuePair<string, object> [] array, int arrayIndex) {
1252 throw new NotSupportedException ();
1255 int ICollection<KeyValuePair<string, object>>.Count {
1256 get { throw new NotSupportedException (); }
1259 bool ICollection<KeyValuePair<string, object>>.IsReadOnly {
1260 get { throw new NotSupportedException (); }
1263 bool ICollection<KeyValuePair<string, object>>.Remove (KeyValuePair<string, object> item) {
1264 throw new NotSupportedException ();
1267 IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator () {
1268 return GetEnumerator ();
1271 IEnumerator IEnumerable.GetEnumerator () {
1272 return ((IEnumerable<KeyValuePair<string, object>>) this).GetEnumerator ();
1275 protected IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
1276 yield return new KeyValuePair<string, object> ("hello", "world");
1280 [Test] //bug #424704
1281 public void NonGenericClassImplementingClosedGenericIDictionary ()
1283 JavaScriptSerializer ser = new JavaScriptSerializer ();
1285 SomeDict dictIn = new SomeDict ();
1287 string s = ser.Serialize (dictIn);
1289 Dictionary<string, object> dictOut = ser.Deserialize<Dictionary<string, object>> (s);
1290 Assert.AreEqual (dictOut.Count, 1, "#1");
1291 Assert.AreEqual (dictOut["hello"], "world", "#2");
1295 public void ConvertToIDictionary ()
1297 JavaScriptSerializer jss = new JavaScriptSerializer ();
1298 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}}";
1299 object input = jss.Deserialize<IDictionary>(json);
1300 IDictionary o = jss.ConvertToType<IDictionary>(input);
1302 Assert.IsTrue (o != null, "#A1");
1303 Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1307 public void ConvertToGenericIDictionary ()
1309 JavaScriptSerializer jss = new JavaScriptSerializer ();
1310 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}}";
1312 object input = jss.Deserialize<IDictionary>(json);
1314 IDictionary <string, object> o = jss.ConvertToType<IDictionary <string, object>>(input);
1315 Assert.IsTrue (o != null, "#A1");
1316 Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1318 IDictionary <object, object> o1 = jss.ConvertToType<IDictionary <object, object>>(input);
1319 Assert.IsTrue (o1 != null, "#B1");
1320 Assert.AreEqual (typeof (Dictionary <object, object>), o1.GetType (), "#B2");
1324 [ExpectedException (typeof (InvalidOperationException))]
1325 public void ConvertToGenericIDictionary_InvalidDefinition ()
1327 JavaScriptSerializer jss = new JavaScriptSerializer ();
1328 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}}";
1330 object input = jss.Deserialize<IDictionary>(json);
1331 IDictionary <int, object> o = jss.ConvertToType<IDictionary <int, object>>(input);
1334 [Test (Description="Bug #655474")]
1335 public void TestRelativeUri()
1337 JavaScriptSerializer ser = new JavaScriptSerializer();
1338 Uri testUri = new Uri("/lala/123", UriKind.Relative);
1339 StringBuilder sb = new StringBuilder();
1341 ser.Serialize(testUri, sb);
1342 Assert.AreEqual ("\"/lala/123\"", sb.ToString ());
1346 public void DeserializeDictionaryOfArrayList ()
1348 var ser = new JavaScriptSerializer ();
1349 string test1 = "{\"key\":{\"subkey\":\"subval\"}}";
1350 string test2 = "{\"key\":[{\"subkey\":\"subval\"}]}";
1352 var ret1 = ser.Deserialize<Dictionary<string, object>>(test1);
1353 Assert.AreEqual (typeof (Dictionary<string, object>), ret1.GetType (), "#1.1");
1354 var ret1v = ret1 ["key"];
1355 Assert.AreEqual (typeof (Dictionary<string, object>), ret1v.GetType (), "#1.2");
1356 var ret1vd = (IDictionary<string,object>) ret1v;
1357 Assert.AreEqual ("subval", ret1vd ["subkey"], "#1.3");
1359 var ret2 = ser.Deserialize<Dictionary<string, object>>(test2);
1360 Assert.AreEqual (typeof (Dictionary<string, object>), ret2.GetType (), "#2.1");
1361 var ret2v = ret2 ["key"];
1362 Assert.AreEqual (typeof (ArrayList), ret2v.GetType (), "#2.2");
1363 var ret2va = (ArrayList) ret2v;
1364 Assert.AreEqual (typeof (Dictionary<string, object>), ret2va [0].GetType (), "#2.3");
1365 var ret2vad = (IDictionary<string,object>) ret2va [0];
1366 Assert.AreEqual ("subval", ret2vad ["subkey"], "#2.4");