IListConverter.cs
上传用户:szgaoree
上传日期:2009-01-05
资源大小:74k
文件大小:2k
- 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 IList.
- /// </summary>
- /// <remarks>
- /// The .Add methods argument type is used to get the type for the list.
- /// </remarks>
- public class IListConverter : IJavaScriptConverter
- {
- public IListConverter() : base()
- {
- }
- public override object Deserialize(IJavaScriptObject o, Type t)
- {
- if(!typeof(IList).IsAssignableFrom(t) || !(o is JavaScriptArray))
- throw new NotSupportedException();
- JavaScriptArray a = (JavaScriptArray)o;
- IList list = (IList)Activator.CreateInstance(t);
- MethodInfo mi = t.GetMethod("Add");
- ParameterInfo pi = mi.GetParameters()[0];
- foreach(IJavaScriptObject i in a)
- {
- list.Add(JavaScriptDeserializer.Deserialize(i, pi.ParameterType));
- }
- return list;
- }
- public override string Serialize(object o)
- {
- if(!(o is IList))
- throw new NotSupportedException();
- StringBuilder sb = new StringBuilder();
- IEnumerable enumerable = (IEnumerable)o;
- bool b = true;
- sb.Append("[");
-
- foreach(object obj in enumerable)
- {
- if(b){ b = false; }
- else{ sb.Append(","); }
- sb.Append(JavaScriptSerializer.Serialize(obj));
- }
- sb.Append("]");
- return sb.ToString();
- }
- public override Type[] SerializableTypes
- {
- get
- {
- return new Type[]{typeof(IList)};
- }
- }
- public override Type[] DeserializableTypes
- {
- get
- {
- return new Type[]{typeof(IList)};
- }
- }
- }
- }