JSON 客户端和服务器端的格式转换(2)


internal class WebExtensionsJavaScriptSerializer : JSONSerializerBase, IJSONSerializer
{
public WebExtensionsJavaScriptSerializer(JSONSerializer serializer) : base(serializer)
{}

public string Serialize(object value)
{
JavaScriptSerializer ser = new JavaScriptSerializer();

List<JavaScriptConverter> converters = new List<JavaScriptConverter>();

if (value != null)
{
Type type = value.GetType();
if (type == typeof(DataTable) || type == typeof(DataRow) || type == typeof(DataSet))
{
converters.Add(new WebExtensionsDataRowConverter());
converters.Add(new WebExtensionsDataTableConverter());
converters.Add(new WebExtensionsDataSetConverter());
}

if (converters.Count > 0)
ser.RegisterConverters(converters);
}

return = ser.Serialize(value);
}
public object Deserialize(string jsonText, Type valueType)
{
// *** Have to use Reflection with a 'dynamic' non constant type instance
JavaScriptSerializer ser = new JavaScriptSerializer();


object result = ser.GetType()
.GetMethod("Deserialize")
.MakeGenericMethod(valueType)
.Invoke(ser, new object[1] { jsonText });
return result;
}
}



internal class WebExtensionsDataTableConverter : JavaScriptConverter
{
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] {typeof (DataTable)}; }
}

public override object Deserialize(IDictionary<string, object> dictionary, Type type,
JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}


下篇介绍如何在ASP.NET的环境下使用JSON和DataTable等的转换,还有介绍使用JQuery的AJAX调用Web Services的生成JSON、相当值得期待。^_^

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjyswp.html