摘要:物件的序列化與反序列化
1.序列化成XML
Public Shared Function XmlSerialiaze(ByVal obj As Object) As String
Dim xs As XmlSerializer = New XmlSerializer(GetType(Object))
Dim ms As MemoryStream = New MemoryStream()
Dim xtw As XmlTextWriter = New XmlTextWriter(ms, System.Text.Encoding.UTF8)
xtw.Formatting = Formatting.Indented
xs.Serialize(xtw, obj)
ms.Seek(0, SeekOrigin.Begin)
Dim sr As StreamReader = New StreamReader(ms)
Dim str As String = sr.ReadToEnd()
xtw.Close()
ms.Close()
Return str
End Function
2.反序列化成XML
Public Shared Function XmlDeserialize(ByVal xml As String, ByVal t As Type) As Object
Dim xs As XmlSerializer = New XmlSerializer(t)
Dim sr As StringReader = New StringReader(xml)
Dim obj As Object = xs.Deserialize(sr)
Return obj
End Function
3. 普通序列化
Public Shared Function Serialize(Of T)(obj As T) As String
Try
Dim formatter As IFormatter = New BinaryFormatter()
Dim stream As New MemoryStream()
formatter.Serialize(stream, obj)
stream.Position = 0
Dim buffer As Byte() = New Byte(stream.Length - 1) {}
stream.Read(buffer, 0, buffer.Length)
stream.Flush()
stream.Close()
Return Convert.ToBase64String(buffer)
Catch ex As Exception
Throw New Exception("Serialize,Detail:" + ex.Message)
End Try
End Function
4. 普通反序列化
Public Shared Function Desrialize(Of T)(obj As T, str As String) As T
Try
obj = Nothing
Dim formatter As IFormatter = New BinaryFormatter()
Dim buffer As Byte() = Convert.FromBase64String(str)
Dim stream As New MemoryStream(buffer)
obj = DirectCast(formatter.Deserialize(stream), T)
stream.Flush()
stream.Close()
Catch ex As Exception
Throw New Exception("Desrialize Error,Detail" + ex.Message)
End Try
Return obj
End Function
人生到處知何似
應似飛鴻踏雪泥