JavaScriptSerializer之DateTime序列化


? ECMAScript 第五版(15.9.5.4)指导toJSON方法的实现应该把一个Date对象处理成UTC时间的ISO 8601格式字符串,例如:"2011-12-28T08:20:31.917Z",这是一个比较通用的一个格式,同时当需要转回Date对象时可以直接将该字串传给Date构造器,例如:new Date("2011-12-28T08:20:31.917Z")

? .NET的JavaScriptSerialzer转化出来的字串类似"/Date(1600237540407)/",这种形式降低了可操作性性,虽然提供了扩展点,但只允许你从一个对象转换成为另外一个对象,而不能转换为自定义的字符串.借助继承Uri实现 IDictionary来进行Hack.

Hack Code

public class DateTimeJavaScriptConverter : JavaScriptConverter
{
	public override object Deserialize(IDictionary dictionary, Type type, JavaScriptSerializer serializer)
	{
		return new JavaScriptSerializer().ConvertToType(dictionary, type);
	}
	
	public override IDictionary Serialize(object obj, JavaScriptSerializer serializer)
	{
		if (!(obj is DateTime)) return null;
		return new CustomString(((DateTime)obj).ToUniversalTime().ToString("O"));
	}
	
	public override IEnumerable SupportedTypes
	{
	  get { return new[] { typeof(DateTime) }; }
	}
	
	private class CustomString : Uri, IDictionary
	{
		public CustomString(string str)
		  : base(str, UriKind.Relative)
		{
		}
		
		void IDictionary.Add(string key, object value)
		{
			throw new NotImplementedException();
		}
		
		bool IDictionary.ContainsKey(string key)
		{
			throw new NotImplementedException();
		}
		
		ICollection IDictionary.Keys
		{
			get { throw new NotImplementedException(); }
		}
		
		bool IDictionary.Remove(string key)
		{
			throw new NotImplementedException();
		}
		
		bool IDictionary.TryGetValue(string key, out object value)
		{
			throw new NotImplementedException();
		}
		
		ICollection IDictionary.Values
		{
			get { throw new NotImplementedException(); }
		}
		
		object IDictionary.this[string key]
		{
			get
			{
			  throw new NotImplementedException();
			}
			set
			{
				throw new NotImplementedException();
			}
		}
		
		void ICollection>.Add(KeyValuePair item)
		{
		  throw new NotImplementedException();
		}
		
		void ICollection>.Clear()
		{
		  throw new NotImplementedException();
		}
		
		bool ICollection>.Contains(KeyValuePair item)
		{
		  throw new NotImplementedException();
		}
		
		void ICollection>.CopyTo(KeyValuePair[] array, int arrayIndex)
		{
		  throw new NotImplementedException();
		}
		
		int ICollection>.Count
		{
		  get { throw new NotImplementedException(); }
		}
		
		bool ICollection>.IsReadOnly
		{
		  get { throw new NotImplementedException(); }
		}
		
		bool ICollection>.Remove(KeyValuePair item)
		{
		  throw new NotImplementedException();
		}
		
		IEnumerator> IEnumerable>.GetEnumerator()
		{
		  throw new NotImplementedException();
		}
		
		IEnumerator IEnumerable.GetEnumerator()
		{
		  throw new NotImplementedException();
		}
	}
}

						  
					  
						
							
C