在ASP.NET 3.5开始,.NET平台下共支持两种序列化方式:
复制代码代码如下:
1.DataContractSerializer
2.JavascriptSerializer
前者主要是根据数据契约(DataContract)进行序列化,通过如下定义的数据契约:
代码
复制代码代码如下:
<DataMember()> _
Public Class Model
<DataMember()> Public Property PropertyA As String
<DataMember()> Public Property PropertyB As String
<IgnoreDataMember()> Public Property PropertyC As String
End Class
其中会根据<DataMember>和<IgnoreDataMember>进行属性是否序列化的判断。
根据数据契约序列化是有缺点的,它的缺点在于在数据类定义之初就需要对属性是否进行序列化进行判定,对于在各处使用的数据模型(Data Model)可能会导致需要全部指定为DataMember,而将无用的属性还有带有默认值(例如Nothing或Null)的属性也同样进行序列化;二是,序列化不能使用属性别名,在业务中定义的名称可能过长,而如果不能指定属性别名就会浪费带宽,导致服务器端与客户端之间的通信变慢。
PageMethod是使用JSON序列化技术的最佳使用场景,在页面实现异步调用(AJAX调用),而不用把所有逻辑都写在服务中,UI方面的业务逻辑判断处理可以写在PageMethod中。在画面插入如下ScriptManager声明并指定EnablePageMethods为True即可将PageMethod打开。
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
很多人看到的实例都是通过MS AJAX进行PageMethod的调用,但因为近两年微软在做ASP.NET与jQuery方面的合作实验,我们其实也可以通过jQuery进行PageMethod的调用。但jQuery的调用方法无法使用GET,只要POST空JSON对象即可实现类GET调用。脚本如下:
复制代码代码如下:
$.ajax({
type: "POST",
url: "Default.aspx/GetJSON",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg);
}
});
PageMethod生命方法如下:
复制代码代码如下:
<WebMethod()> _
Public Shared Function GetJSON() As String
Dim list As New List(Of Model)
For index As Integer = 0 To 1000
Dim m_JSON As New Model With {.PropertyA = "Hello", .PropertyB = "World"}
list.Add(m_JSON)
Next
Dim str As String = JSONHelper.Serialize(list)
Return str
End Function
[code]
其中Model类定义如下:
[code]
<DataContract()> _
Public Class Model
<DataMember(EmitdefaultValue:=False, IsRequired:=False, Name:="A")> Public Property PropertyA As String
<DataMember(EmitdefaultValue:=False, IsRequired:=False, Name:="B")> Public Property PropertyB As String
<DataMember(EmitdefaultValue:=False, IsRequired:=False, Name:="C")> Public Property PropertyC As String
End Class
序列化的Model实例结果为:
{"A":"Hello","B":"World"}
这里再给大家提供一下网上比较流行的JSON转换类,使用的是JavascriptSerializer,代码如下:
复制代码代码如下:
Public Class JSONHelper
Public Shared Function Serialize(Of T)(ByVal obj As T) As String
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType())
Dim ms As New MemoryStream()
serializer.WriteObject(ms, obj)
Dim retVal As String = Encoding.Default.GetString(ms.ToArray())
Return retVal
End Function
Public Shared Function Deserialize(Of T)(ByVal json As String) As T
Dim obj As T = Activator.CreateInstance(Of T)()
Dim ms As New MemoryStream(Encoding.Unicode.GetBytes(json))
Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType())
obj = CType(serializer.ReadObject(ms), T)
ms.Close()
Return obj
End Function
End Class