[.Net] JSonSerializer, classe pour sérialiser vos objets

json-serializer

Voila une classe dotnet bien pratique qui permet de sérialiser des objets en json.

Imports System.IO
Imports System.Text
Imports System.Runtime.Serialization

Public Class JSONSerializer
    Public Shared Function Serialize(ByVal BaseType As Object) As String
        Dim ExactName As String = BaseType.GetType.ToString
        Dim Ser As String = p_Serialize(BaseType)
        Dim oList As New List(Of String)
        oList.Add(ExactName)
        oList.Add(Ser)
        Return p_Serialize(oList)
    End Function
    Public Shared Function Deserialize(ByVal s As String) As Object
        Dim oList As New List(Of String)
        oList = DirectCast(p_Deserialize(s, oList), List(Of String))
        Dim Instance As Object = Nothing
        Instance = Activator.CreateInstance(Type.GetType(oList.Item(0)))
        Return p_Deserialize(oList.Item(1), Instance)
    End Function

    Private Shared Function GetStringFromMemoryStream(ByVal m As MemoryStream) As String
        If (m Is Nothing) Or m.Length = 0 Then
            Return ""
        End If
        m.Flush()
        m.Position = 0
        Dim UTF8 As Encoding = UTF8Encoding.UTF8
        Dim sr As New StreamReader(m, UTF8Encoding.UTF8)
        Dim s As String = sr.ReadToEnd()
        Return s
    End Function
    Private Shared Function GetMemoryStreamFromString(ByVal s As String) As MemoryStream
        If (s Is Nothing) OrElse s.Length = 0 Then
            Return Nothing
        End If
        Dim a() As Byte = System.Text.Encoding.UTF8.GetBytes(s)
        Dim m As New System.IO.MemoryStream(a, True)
        m.Position = 0
        Return m
    End Function
    Private Shared Function p_Serialize(ByVal BaseType As Object) As String
        If BaseType Is Nothing Then
            Throw New ArgumentNullException()
        End If
        Dim dcs As New DataContractSerializer(BaseType.[GetType]())
        Dim ms As New MemoryStream()
        dcs.WriteObject(ms, BaseType)

        Return Encoding.UTF8.GetString(ms.GetBuffer(), 0, CInt(ms.Position))
    End Function
    Private Shared Function p_Deserialize(ByVal s As String, ByVal BaseType As Object) As Object
        Dim dcs As New DataContractSerializer(BaseType.GetType())
        Dim m As MemoryStream = GetMemoryStreamFromString(s)
        If m IsNot Nothing Then
            BaseType = dcs.ReadObject(m)
        End If
        Return BaseType
    End Function
End Class

Leave a Reply

Your email address will not be published. Required fields are marked *