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 TestDeserializeNonGenericOverload()
421 JavaScriptSerializer ser = new JavaScriptSerializer();
422 Assert.IsNull(ser.Deserialize("", typeof(X)));
426 string x = ser.Serialize(s);
428 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");
430 X n = ser.Deserialize(x, typeof(X)) as X;
431 Assert.AreEqual(s, n, "#A2");
435 public void TestDeserializeTypeResolver ()
438 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}]}";
440 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}]}";
442 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}]}";
444 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
448 string s = ser.Serialize (x);
449 Assert.AreEqual (expected, s, "#A1");
451 X x2 = ser.Deserialize<X> (s);
452 Assert.AreEqual (x, x2, "#A2");
456 public void TestDeserializeBugs () {
457 JavaScriptSerializer ser = new JavaScriptSerializer ();
461 string x = ser.Serialize (s);
462 bug n = ser.Deserialize<bug> (x);
463 Assert.AreEqual (s, n);
465 // Should check correctness with .Net GA:
466 //js = ser.Serialize (Color.Red);
467 //Color ccc = ser.Deserialize<Color> (js);
468 //string xml = @"<root><node attr=""xxx""/></root>";
470 //XmlDocument doc = new XmlDocument ();
472 //string js = ser.Serialize (doc);
473 //DataTable table = new DataTable();
474 //table.Columns.Add ("col1", typeof (int));
475 //table.Columns.Add ("col2", typeof (float));
476 //table.Rows.Add (1, 1f);
477 //table.Rows.Add (234234, 2.4f);
479 //string js = ser.Serialize (table);
482 static void FieldsEqual (object expected, object actual) {
483 Assert.AreEqual (expected.GetType (), actual.GetType ());
484 FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
485 foreach (FieldInfo info in infos) {
486 object value1 = info.GetValue (expected);
487 object value2 = info.GetValue (actual);
488 if (value1 is IEnumerable) {
489 IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
491 foreach (object x in (IEnumerable) value1) {
492 if (!yenum.MoveNext ())
493 Assert.Fail (info.Name + " index:" + index);
495 if (x is DictionaryEntry) {
496 DictionaryEntry entry = (DictionaryEntry)x;
497 IDictionary dict = (IDictionary) value2;
498 Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
501 Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
503 Assert.IsFalse (yenum.MoveNext (), info.Name);
506 Assert.AreEqual (value1, value2, info.Name);
512 [ExpectedException (typeof (ArgumentNullException))]
513 public void TestDeserialize1 () {
514 JavaScriptSerializer ser = new JavaScriptSerializer ();
515 ser.Deserialize<string> (null);
519 [ExpectedException (typeof (ArgumentNullException))]
520 public void TestDeserializeNullConverter () {
521 JavaScriptSerializer ser = new JavaScriptSerializer ();
522 ser.RegisterConverters (null);
526 [SetCulture ("en-US")]
527 public void TestDeserializeConverter () {
528 JavaScriptSerializer ser = new JavaScriptSerializer ();
529 List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
530 list.Add (new MyJavaScriptConverter ());
531 list.Add (new CultureInfoConverter ());
532 ser.RegisterConverters (list);
533 string result = ser.Serialize (new X [] { new X (), new X () });
534 Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
535 result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
539 public void TestDeserializeConverter1 () {
540 JavaScriptSerializer serializer = new JavaScriptSerializer ();
542 serializer.RegisterConverters (new JavaScriptConverter [] {new ListItemCollectionConverter()});
544 ListBox ListBox1 = new ListBox ();
545 ListBox1.Items.Add ("a1");
546 ListBox1.Items.Add ("a2");
547 ListBox1.Items.Add ("a3");
549 string x = serializer.Serialize (ListBox1.Items);
550 ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
551 Assert.AreEqual (3, recoveredList.Count);
555 public void TestSerialize1 () {
556 JavaScriptSerializer ser = new JavaScriptSerializer ();
557 Assert.AreEqual("null", ser.Serialize(null));
559 string js = ser.Serialize (1234);
560 Assert.AreEqual ("1234", js);
561 Assert.AreEqual (1234, ser.Deserialize<int> (js));
562 js = ser.Serialize (1.1);
563 Assert.AreEqual ("1.1", js);
564 Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
565 char [] chars = "faskjhfasd0981234".ToCharArray ();
566 js = ser.Serialize (chars);
567 char[] actual = ser.Deserialize<char[]> (js);
568 Assert.AreEqual (chars.Length, actual.Length);
569 for (int i = 0; i < chars.Length; i++)
570 Assert.AreEqual (chars[i], actual[i]);
572 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{|}~""";
573 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{|}~";
575 string serRes = ser.Serialize (data);
576 Assert.AreEqual (expected, serRes);
577 string deserRes = ser.Deserialize<string> (serRes);
578 Assert.AreEqual (data, deserRes);
582 [ExpectedException (typeof (ArgumentNullException))]
583 [Category ("NotDotNet")]
584 public void TestSerialize2 () {
585 JavaScriptSerializer ser = new JavaScriptSerializer ();
586 ser.Serialize ("aaa", (StringBuilder)null);
589 static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
592 public void TestSerializeDate () {
593 JavaScriptSerializer ser = new JavaScriptSerializer ();
594 DateTime now = new DateTime (633213894056010000L);
596 string actual = ser.Serialize (now);
597 DateTime dateTime = now.ToUniversalTime ();
598 long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
600 object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
601 Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
602 Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
606 public void TestSerializeEnum () {
607 JavaScriptSerializer ser = new JavaScriptSerializer ();
608 string result = ser.Serialize (MyEnum.BBB);
609 Assert.AreEqual ("1", result);
610 Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
613 class MyJavaScriptConverter : JavaScriptConverter
615 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
616 throw new Exception ("The method or operation is not implemented.");
619 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
620 Array a = (Array) obj;
621 Dictionary<string, object> d = new Dictionary<string, object> ();
625 //throw new Exception ("The method or operation is not implemented.");
628 public override IEnumerable<Type> SupportedTypes {
630 yield return typeof (X[]);
635 sealed class CultureInfoConverter : JavaScriptConverter
637 static readonly Type typeofCultureInfo = typeof (CultureInfo);
638 public override IEnumerable<Type> SupportedTypes {
639 get { yield return typeofCultureInfo; }
642 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
643 throw new NotSupportedException ();
646 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
647 CultureInfo ci = (CultureInfo)obj;
650 Dictionary<string, object> d = new Dictionary<string, object> ();
651 d.Add ("name", ci.Name);
652 d.Add ("numberFormat", ci.NumberFormat);
653 d.Add ("dateTimeFormat", ci.DateTimeFormat);
658 public class ListItemCollectionConverter : JavaScriptConverter
660 public override IEnumerable<Type> SupportedTypes {
661 //Define the ListItemCollection as a supported type.
662 get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
665 public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
666 ListItemCollection listType = obj as ListItemCollection;
668 if (listType != null) {
669 // Create the representation.
670 Dictionary<string, object> result = new Dictionary<string, object> ();
671 ArrayList itemsList = new ArrayList ();
672 foreach (ListItem item in listType) {
673 //Add each entry to the dictionary.
674 Dictionary<string, object> listDict = new Dictionary<string, object> ();
675 listDict.Add ("Value", item.Value);
676 listDict.Add ("Text", item.Text);
677 itemsList.Add (listDict);
679 result ["List"] = itemsList;
683 return new Dictionary<string, object> ();
686 public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
687 if (dictionary == null)
688 throw new ArgumentNullException ("dictionary");
690 if (type == typeof (ListItemCollection)) {
691 // Create the instance to deserialize into.
692 ListItemCollection list = new ListItemCollection ();
694 // Deserialize the ListItemCollection's items.
695 ArrayList itemsList = (ArrayList) dictionary ["List"];
696 for (int i = 0; i < itemsList.Count; i++)
697 list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
706 public void DeserializeObject () {
707 object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
708 Assert.IsNotNull (o as Dictionary<string, object>, "type");
709 Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
710 Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
711 Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
712 object [] array = (object []) dictionary ["Array"];
713 Assert.AreEqual (true, (bool) array [0], "array [0]");
714 Assert.AreEqual (false, (bool) array [1], "array [1]");
715 Assert.AreEqual (0, (int) array [2], "array [2]");
719 public void DeserializeObject2 ()
721 JavaScriptSerializer ser = new JavaScriptSerializer ();
723 string s = ser.Serialize (y);
724 object y2 = ser.DeserializeObject (s);
725 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
729 public void DeserializeObject3 ()
731 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
733 string s = ser.Serialize (y);
734 object y2 = ser.DeserializeObject (s);
735 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
739 public void DeserializeObject4 ()
741 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
743 string s = ser.Serialize (y);
744 object y2 = ser.DeserializeObject (s);
745 Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
746 Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
747 Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
748 Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
749 Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
753 [ExpectedException(typeof(ArgumentNullException))]
754 public void SerializeWithResolverDeserializeWithout ()
756 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
758 string s = ser.Serialize (y);
759 ser = new JavaScriptSerializer ();
760 object y2 = ser.DeserializeObject (s);
764 public void SerializeWithoutResolverDeserializeWith ()
766 JavaScriptSerializer ser = new JavaScriptSerializer ();
768 string s = ser.Serialize (y);
769 ser = new JavaScriptSerializer (new SimpleTypeResolver ());
770 object y2 = ser.DeserializeObject (s);
771 Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
777 public string s1 = "s1";
783 public string s2 = "s2";
788 public B b1 = new B ();
789 public B b2 = new D ();
793 public void SerializeDerivedType ()
795 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
797 string s = ser.Serialize (b);
798 B b2 = ser.Deserialize<B> (s);
799 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
803 public void SerializeDerivedType2 ()
805 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
807 string s = ser.Serialize (b);
808 B b2 = (B)ser.DeserializeObject (s);
809 Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
813 public void SerializeContainedDerivedType ()
815 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
817 string s = ser.Serialize (c);
818 C c2 = ser.Deserialize<C> (s);
819 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
820 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
824 public void SerializeContainedDerivedType2 ()
826 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
828 string s = ser.Serialize (c);
829 C c2 = (C)ser.DeserializeObject (s);
830 Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
831 Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
835 public void SerializeWithTypeConverter ()
837 JavaScriptSerializer ser = new JavaScriptSerializer ();
838 MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
839 string s = ser.Serialize (uri);
840 MyUri uri2 = ser.Deserialize<MyUri> (s);
841 Assert.AreEqual (uri, uri2);
845 public void SerializeWithTypeConverter2 ()
847 JavaScriptSerializer ser = new JavaScriptSerializer ();
848 MyPointContainer pc = new MyPointContainer(new Point(15, 16));
849 string s = ser.Serialize(pc);
850 MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
854 public void MaxJsonLengthDeserializeObject ()
856 JavaScriptSerializer ser = new JavaScriptSerializer ();
857 ser.MaxJsonLength = 16;
858 object o = ser.DeserializeObject ("{s:'1234567890'}");
862 [ExpectedException(typeof(ArgumentException))]
863 public void MaxJsonLengthDeserializeObjectToLong ()
865 JavaScriptSerializer ser = new JavaScriptSerializer ();
866 ser.MaxJsonLength = 15;
867 object o = ser.DeserializeObject ("{s:'1234567890'}");
871 public void MaxJsonLengthSerialize ()
873 JavaScriptSerializer ser = new JavaScriptSerializer ();
874 ser.MaxJsonLength = 9;
876 string s = ser.Serialize (y);
880 [ExpectedException (typeof (InvalidOperationException))]
881 public void MaxJsonLengthSerializeToLong ()
883 JavaScriptSerializer ser = new JavaScriptSerializer ();
884 ser.MaxJsonLength = 8;
886 string s = ser.Serialize (y);
890 public void RecursionLimitDeserialize1 ()
892 JavaScriptSerializer ser = new JavaScriptSerializer ();
893 ser.RecursionLimit = 3;
894 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
898 public void RecursionLimitDeserialize2 ()
900 JavaScriptSerializer ser = new JavaScriptSerializer ();
901 ser.RecursionLimit = 2;
902 YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
906 public void RecursionLimitDeserialize3 ()
908 JavaScriptSerializer ser = new JavaScriptSerializer ();
909 ser.RecursionLimit = 1;
910 object o = ser.DeserializeObject ("\"xxx\"");
914 [ExpectedException(typeof(ArgumentException))]
915 public void RecursionLimitDeserializeToDeep ()
917 JavaScriptSerializer ser = new JavaScriptSerializer ();
918 ser.RecursionLimit = 2;
919 YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
923 public void RecursionLimitSerialize ()
925 JavaScriptSerializer ser = new JavaScriptSerializer ();
926 ser.RecursionLimit = 3;
928 string s = ser.Serialize (yy);
932 [ExpectedException(typeof(ArgumentException))]
933 public void RecursionLimitSerializeToDeep ()
935 JavaScriptSerializer ser = new JavaScriptSerializer ();
936 ser.RecursionLimit = 2;
938 string s = ser.Serialize (yy);
942 public void RecursionLimitSerialize2 ()
944 JavaScriptSerializer ser = new JavaScriptSerializer ();
945 ser.RecursionLimit = 2;
947 StringBuilder b = new StringBuilder ();
948 bool caughtException = false;
950 ser.Serialize (yy, b);
953 caughtException = true;
955 Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
956 Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
960 public void SimpleTypeResolver ()
962 JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
964 string s = ser.Serialize (yy);
965 string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
967 Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
969 expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
970 Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
973 public class CustomResolver : JavaScriptTypeResolver
975 public CustomResolver ()
980 public override Type ResolveType (string id)
982 ResolvedIds.Add (id);
998 return typeof (long);
1001 return typeof (string);
1004 return typeof(Point);
1009 public override string ResolveTypeId (Type type)
1012 throw new ArgumentNullException ("type");
1015 ResolvedTypes.Add (type.Name);
1017 if (type == typeof (YY))
1020 if (type == typeof (Y))
1023 if (type == typeof (X))
1026 if (type == typeof (int))
1029 if (type == typeof (long))
1032 if (type == typeof (string))
1035 if (type == typeof(Point))
1041 public static List<string> ResolvedTypes {
1043 if (resolvedTypes == null) {
1044 resolvedTypes = new List<string> ();
1046 return resolvedTypes;
1050 public static List<string> ResolvedIds {
1052 if (resolvedIds == null) {
1053 resolvedIds = new List<string> ();
1059 public static void Reset ()
1062 resolvedTypes = null;
1065 private static List<string> resolvedTypes;
1066 private static List<string> resolvedIds;
1070 [NUnit.Framework.Category ("NotWorking")]
1071 public void CustomTypeResolver ()
1073 JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
1077 string s = ser.Serialize (x);
1079 CustomResolver.Reset ();
1080 X x1 = (X) ser.DeserializeObject (s);
1081 Assert.IsTrue (x.Equals (x1), "x != x1");
1083 CustomResolver.Reset ();
1084 X x2 = ser.Deserialize<X> (s);
1085 Assert.IsTrue (x.Equals (x2), "x != x2");
1089 public void InfinityAndNaN ()
1091 JavaScriptSerializer ser = new JavaScriptSerializer ();
1093 double nan = Double.NaN;
1094 string s = ser.Serialize (nan);
1095 Assert.AreEqual (s, "NaN", "#A1");
1096 nan = (double)ser.DeserializeObject (s);
1097 Assert.AreEqual (Double.NaN, nan, "#A2");
1098 nan = (double)ser.Deserialize <double> (s);
1099 Assert.AreEqual (Double.NaN, nan, "#A3");
1101 double infinity = Double.PositiveInfinity;
1102 s = ser.Serialize (infinity);
1103 Assert.AreEqual (s, "Infinity", "#B1");
1104 infinity = (double)ser.DeserializeObject (s);
1105 Assert.AreEqual (Double.PositiveInfinity, infinity, "#B2");
1106 infinity = ser.Deserialize <double> (s);
1107 Assert.AreEqual (Double.PositiveInfinity, infinity, "#B3");
1109 infinity = Double.NegativeInfinity;
1110 s = ser.Serialize (infinity);
1111 Assert.AreEqual (s, "-Infinity", "#C1");
1112 infinity = (double)ser.DeserializeObject (s);
1113 Assert.AreEqual (Double.NegativeInfinity, infinity, "#C2");
1114 infinity = ser.Deserialize <double> (s);
1115 Assert.AreEqual (Double.NegativeInfinity, infinity, "#C3");
1117 var dict = new Dictionary <string, object> ();
1118 dict.Add ("A", Double.NaN);
1119 dict.Add ("B", Double.PositiveInfinity);
1120 dict.Add ("C", Double.NegativeInfinity);
1121 s = ser.Serialize (dict);
1122 Assert.AreEqual ("{\"A\":NaN,\"B\":Infinity,\"C\":-Infinity}", s, "#D1");
1124 dict = (Dictionary <string, object>)ser.DeserializeObject (s);
1125 Assert.AreEqual (Double.NaN, dict ["A"], "#D2");
1126 Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D3");
1127 Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D4");
1129 dict = (Dictionary <string, object>)ser.Deserialize <Dictionary <string, object>> (s);
1130 Assert.AreEqual (Double.NaN, dict ["A"], "#D5");
1131 Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D6");
1132 Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D7");
1134 var arr = new ArrayList () {
1136 Double.PositiveInfinity,
1137 Double.NegativeInfinity};
1138 s = ser.Serialize (arr);
1139 Assert.AreEqual ("[NaN,Infinity,-Infinity]", s, "#E1");
1141 object[] arr2 = (object[])ser.DeserializeObject (s);
1142 Assert.AreEqual (3, arr2.Length, "#E2");
1143 Assert.AreEqual (Double.NaN, arr2 [0], "#E3");
1144 Assert.AreEqual (Double.PositiveInfinity, arr2 [1], "#E4");
1145 Assert.AreEqual (Double.NegativeInfinity, arr2 [2], "#E5");
1147 arr = ser.Deserialize <ArrayList> (s);
1148 Assert.AreEqual (3, arr.Count, "#E6");
1149 Assert.AreEqual (Double.NaN, arr [0], "#E7");
1150 Assert.AreEqual (Double.PositiveInfinity, arr [1], "#E8");
1151 Assert.AreEqual (Double.NegativeInfinity, arr [2], "#E9");
1155 public void StandalonePrimitives ()
1157 JavaScriptSerializer ser = new JavaScriptSerializer ();
1162 o = ser.DeserializeObject ("1");
1163 Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A1");
1165 Assert.AreEqual (1, i, "#A2");
1166 o =ser.DeserializeObject ("-1");
1167 Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A3");
1169 Assert.AreEqual (-1, i, "#A4");
1171 o = ser.DeserializeObject ("2147483649");
1172 Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B1");
1174 Assert.AreEqual (2147483649, l, "#B2");
1175 o = ser.DeserializeObject ("-2147483649");
1176 Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B3");
1178 Assert.AreEqual (-2147483649, l, "#B4");
1180 o = ser.DeserializeObject ("9223372036854775808");
1181 Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C1");
1182 decimal d = (decimal)o;
1183 Assert.AreEqual (9223372036854775808m, d, "#C2");
1184 o = ser.DeserializeObject ("-9223372036854775809");
1185 Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C3");
1187 Assert.AreEqual (-9223372036854775809m, d, "#C4");
1189 o = ser.DeserializeObject ("79228162514264337593543950336");
1190 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D1");
1191 double db = (double)o;
1192 Assert.AreEqual (79228162514264337593543950336.0, db, "#D2");
1193 o = ser.DeserializeObject ("-79228162514264337593543950336");
1194 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D3");
1196 Assert.AreEqual (-79228162514264337593543950336.0, db, "#D4");
1198 o = ser.DeserializeObject ("\"test string\"");
1199 Assert.AreEqual (typeof (global::System.String), o.GetType (), "#E1");
1200 string s = (string)o;
1201 Assert.AreEqual ("test string", s, "#E2");
1203 o = ser.DeserializeObject ("true");
1204 Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F1");
1206 Assert.AreEqual (true, b, "#F2");
1208 o = ser.DeserializeObject ("false");
1209 Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F3");
1211 Assert.AreEqual (false, b, "#F4");
1213 o = ser.DeserializeObject ("-1.7976931348623157E+308");
1214 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G1");
1216 Assert.AreEqual (Double.MinValue, db, "#G2");
1218 o = ser.DeserializeObject ("1.7976931348623157E+308");
1219 Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G3");
1221 Assert.AreEqual (Double.MaxValue, db, "#G4");
1224 class SomeDict : IDictionary<string, object>
1226 void IDictionary<string, object>.Add (string key, object value) {
1227 throw new NotSupportedException ();
1230 bool IDictionary<string, object>.ContainsKey (string key) {
1231 throw new NotSupportedException ();
1234 ICollection<string> IDictionary<string, object>.Keys {
1235 get { throw new NotSupportedException (); }
1238 bool IDictionary<string, object>.Remove (string key) {
1239 throw new NotSupportedException ();
1242 bool IDictionary<string, object>.TryGetValue (string key, out object value) {
1243 throw new NotSupportedException ();
1246 ICollection<object> IDictionary<string, object>.Values {
1247 get { throw new NotSupportedException (); }
1250 object IDictionary<string, object>.this [string key] {
1251 get { throw new NotSupportedException (); }
1252 set { throw new NotSupportedException (); }
1255 void ICollection<KeyValuePair<string, object>>.Add (KeyValuePair<string, object> item) {
1256 throw new NotSupportedException ();
1259 void ICollection<KeyValuePair<string, object>>.Clear () {
1260 throw new NotSupportedException ();
1263 bool ICollection<KeyValuePair<string, object>>.Contains (KeyValuePair<string, object> item) {
1264 throw new NotSupportedException ();
1267 void ICollection<KeyValuePair<string, object>>.CopyTo (KeyValuePair<string, object> [] array, int arrayIndex) {
1268 throw new NotSupportedException ();
1271 int ICollection<KeyValuePair<string, object>>.Count {
1272 get { throw new NotSupportedException (); }
1275 bool ICollection<KeyValuePair<string, object>>.IsReadOnly {
1276 get { throw new NotSupportedException (); }
1279 bool ICollection<KeyValuePair<string, object>>.Remove (KeyValuePair<string, object> item) {
1280 throw new NotSupportedException ();
1283 IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator () {
1284 return GetEnumerator ();
1287 IEnumerator IEnumerable.GetEnumerator () {
1288 return ((IEnumerable<KeyValuePair<string, object>>) this).GetEnumerator ();
1291 protected IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
1292 yield return new KeyValuePair<string, object> ("hello", "world");
1296 [Test] //bug #424704
1297 public void NonGenericClassImplementingClosedGenericIDictionary ()
1299 JavaScriptSerializer ser = new JavaScriptSerializer ();
1301 SomeDict dictIn = new SomeDict ();
1303 string s = ser.Serialize (dictIn);
1305 Dictionary<string, object> dictOut = ser.Deserialize<Dictionary<string, object>> (s);
1306 Assert.AreEqual (dictOut.Count, 1, "#1");
1307 Assert.AreEqual (dictOut["hello"], "world", "#2");
1311 public void ConvertToIDictionary ()
1313 JavaScriptSerializer jss = new JavaScriptSerializer ();
1314 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}}";
1315 object input = jss.Deserialize<IDictionary>(json);
1316 IDictionary o = jss.ConvertToType<IDictionary>(input);
1318 Assert.IsTrue (o != null, "#A1");
1319 Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1323 public void ConvertToGenericIDictionary ()
1325 JavaScriptSerializer jss = new JavaScriptSerializer ();
1326 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}}";
1328 object input = jss.Deserialize<IDictionary>(json);
1330 IDictionary <string, object> o = jss.ConvertToType<IDictionary <string, object>>(input);
1331 Assert.IsTrue (o != null, "#A1");
1332 Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1334 IDictionary <object, object> o1 = jss.ConvertToType<IDictionary <object, object>>(input);
1335 Assert.IsTrue (o1 != null, "#B1");
1336 Assert.AreEqual (typeof (Dictionary <object, object>), o1.GetType (), "#B2");
1340 [ExpectedException (typeof (InvalidOperationException))]
1341 public void ConvertToGenericIDictionary_InvalidDefinition ()
1343 JavaScriptSerializer jss = new JavaScriptSerializer ();
1344 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}}";
1346 object input = jss.Deserialize<IDictionary>(json);
1347 IDictionary <int, object> o = jss.ConvertToType<IDictionary <int, object>>(input);
1350 [Test (Description="Bug #655474")]
1351 public void TestRelativeUri()
1353 JavaScriptSerializer ser = new JavaScriptSerializer();
1354 Uri testUri = new Uri("/lala/123", UriKind.Relative);
1355 StringBuilder sb = new StringBuilder();
1357 ser.Serialize(testUri, sb);
1358 Assert.AreEqual ("\"/lala/123\"", sb.ToString ());
1362 public void DeserializeDictionaryOfArrayList ()
1364 var ser = new JavaScriptSerializer ();
1365 string test1 = "{\"key\":{\"subkey\":\"subval\"}}";
1366 string test2 = "{\"key\":[{\"subkey\":\"subval\"}]}";
1368 var ret1 = ser.Deserialize<Dictionary<string, object>>(test1);
1369 Assert.AreEqual (typeof (Dictionary<string, object>), ret1.GetType (), "#1.1");
1370 var ret1v = ret1 ["key"];
1371 Assert.AreEqual (typeof (Dictionary<string, object>), ret1v.GetType (), "#1.2");
1372 var ret1vd = (IDictionary<string,object>) ret1v;
1373 Assert.AreEqual ("subval", ret1vd ["subkey"], "#1.3");
1375 var ret2 = ser.Deserialize<Dictionary<string, object>>(test2);
1376 Assert.AreEqual (typeof (Dictionary<string, object>), ret2.GetType (), "#2.1");
1377 var ret2v = ret2 ["key"];
1378 Assert.AreEqual (typeof (ArrayList), ret2v.GetType (), "#2.2");
1379 var ret2va = (ArrayList) ret2v;
1380 Assert.AreEqual (typeof (Dictionary<string, object>), ret2va [0].GetType (), "#2.3");
1381 var ret2vad = (IDictionary<string,object>) ret2va [0];
1382 Assert.AreEqual ("subval", ret2vad ["subkey"], "#2.4");
1385 class ClassWithNullableEnum
1387 public MyEnum? Value { get; set; }
1391 public void DeserializeNullableEnum ()
1393 var jsonValues = new Dictionary<string, MyEnum?> {
1394 { "{\"Value\":0}", MyEnum.AAA},
1395 { "{\"Value\":\"0\"}", MyEnum.AAA},
1396 { "{\"Value\":null}", null}
1399 var ser = new JavaScriptSerializer ();
1401 foreach (var kv in jsonValues)
1403 var obj = ser.Deserialize<ClassWithNullableEnum> (kv.Key);
1404 Assert.AreEqual (kv.Value, obj.Value);