1.在專案中加入參考System.Runtime.Serialization命名空間
2.在類別中加入Imports System.Runtime.Serialization.Json
'''
''' 物件序列化成Json格式
'''
'''物件型別
''' 物件
'''Json格式
Public Shared Function JsonSerialize(Of T)(ByVal o As T) As String
Return JsonSerialize(Of T)(o, Encoding.Default)
End Function
'''
''' 物件序列化成Json格式
'''
'''物件型別
''' 物件
''' 編碼
'''Json格式
Public Shared Function JsonSerialize(Of T)(ByVal o As T, ByVal encoding As Encoding) As String
Using ms As New MemoryStream
Dim json As New DataContractJsonSerializer(GetType(T))
json.WriteObject(ms, o)
Using sr As New StreamReader(ms, encoding)
ms.Position = 0
Return sr.ReadToEnd()
End Using
End Using
End Function
'''
''' Json格式反序列化成物件
'''
'''物件型別
''' Json格式
'''物件
Public Shared Function JsonDeserialize(Of T)(ByVal s As String) As T
Return JsonDeserialize(Of T)(s, Encoding.Default)
End Function
'''
''' Json格式反序列化成物件
'''
'''物件型別
''' Json格式
''' 編碼
'''物件
Public Shared Function JsonDeserialize(Of T)(ByVal s As String, ByVal encoding As Encoding) As T
Using ms As New MemoryStream(encoding.GetBytes(s))
Dim json As New DataContractJsonSerializer(GetType(T))
ms.Position = 0
Return json.ReadObject(ms)
End Using
End Function
沒有留言:
張貼留言