- /*
- * MS 05-12-21 added Deserialize for Hashtables
- * JavaScript object will now include the type for key and value
- *
- *
- *
- */
- using System;
- using System.Reflection;
- using System.Text;
- using System.Collections;
- using System.Collections.Specialized;
- namespace AjaxPro
- {
- /// <summary>
- /// Provides methods to serialize and deserialize an object that implements IDictionary.
- /// </summary>
- public class IDictionaryConverter : IJavaScriptConverter
- {
- public IDictionaryConverter() : base()
- {
- }
- public override object Deserialize(IJavaScriptObject o, Type t)
- {
- if (!(o is JavaScriptArray))
- throw new NotSupportedException();
- JavaScriptArray a = (JavaScriptArray)o;
- for (int i = 0; i < a.Count; i++)
- if (!(a[i] is JavaScriptArray))
- throw new NotSupportedException();
- IDictionary d = (IDictionary)Activator.CreateInstance(t);
- object key;
- object value;
- JavaScriptArray aa;
- for (int i = 0; i < a.Count; i++)
- {
- aa = (JavaScriptArray)a[i];
- key = JavaScriptDeserializer.Deserialize((IJavaScriptObject)aa[0], Type.GetType(((JavaScriptString)aa[2]).ToString()));
- value = JavaScriptDeserializer.Deserialize((IJavaScriptObject)aa[1], Type.GetType(((JavaScriptString)aa[3]).ToString()));
- d.Add(key, value);
- }
- return d;
- }
- public override string Serialize(object o)
- {
- if(!(o is IDictionary))
- throw new NotSupportedException();
- StringBuilder sb = new StringBuilder();
- IDictionary dic = (IDictionary)o;
- IDictionaryEnumerator enumerable = dic.GetEnumerator();
- enumerable.Reset();
- bool b = true;
- sb.Append("[");
- while(enumerable.MoveNext())
- {
- if(b){ b = false; }
- else{ sb.Append(","); }
- sb.Append('[');
- sb.Append(JavaScriptSerializer.Serialize(enumerable.Key));
- sb.Append(',');
- sb.Append(JavaScriptSerializer.Serialize(enumerable.Value));
- sb.Append(',');
- sb.Append(JavaScriptSerializer.SerializeString(enumerable.Key.GetType().FullName));
- sb.Append(',');
- sb.Append(JavaScriptSerializer.SerializeString(enumerable.Value.GetType().FullName));
- sb.Append(']');
- }
- sb.Append("]");
- return sb.ToString();
- }
- public override Type[] DeserializableTypes
- {
- get
- {
- return new Type[] { typeof(Hashtable) };
- }
- }
- public override Type[] SerializableTypes
- {
- get
- {
- return new Type[]{typeof(IDictionary), typeof(Hashtable)};
- }
- }
- }
- }