是的,C# 的 JavaScriptSerializer
類支持自定義類型。但是,為了使自定義類型能夠被序列化和反序列化,你需要實現 ISerializable
接口,并定義 SerializeObject
和 DeserializeObject
方法。
以下是一個簡單的示例,展示了如何為自定義類型實現 ISerializable
接口:
using System;
using System.Web.Script.Serialization;
public class CustomType : ISerializable
{
public int Id { get; set; }
public string Name { get; set; }
// 實現 ISerializable 接口的 SerializeObject 方法
public void SerializeObject(JavaScriptSerializer serializer)
{
serializer.RegisterConverters(new JavaScriptConverter[] { new CustomTypeJavaScriptConverter() });
serializer.Serialize(this, typeof(CustomType));
}
// 實現 ISerializable 接口的 DeserializeObject 方法
public static CustomType DeserializeObject(JavaScriptSerializer serializer, object obj)
{
return (CustomType)serializer.DeserializeObject(obj.ToString(), typeof(CustomType));
}
}
public class CustomTypeJavaScriptConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new[] { typeof(CustomType) }; }
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
var customType = (CustomType)obj;
var dictionary = new Dictionary<string, object>
{
{ "Id", customType.Id },
{ "Name", customType.Name }
};
return dictionary;
}
}
在這個示例中,我們創建了一個名為 CustomType
的自定義類型,并實現了 ISerializable
接口。我們還創建了一個名為 CustomTypeJavaScriptConverter
的自定義 JavaScript 轉換器,用于處理 CustomType
類型的序列化和反序列化。
現在,你可以使用 JavaScriptSerializer
類來序列化和反序列化 CustomType
類型的對象:
var serializer = new JavaScriptSerializer();
// 創建一個 CustomType 對象
var customType = new CustomType { Id = 1, Name = "John Doe" };
// 序列化 CustomType 對象
customType.SerializeObject(serializer);
// 反序列化 CustomType 對象
var deserializedCustomType = CustomType.DeserializeObject(serializer, serializer.Parse(customType.SerializeObject(serializer).ToString()));