vb.Net操作josn

2462 ワード

Imports System.Runtime.Serialization.Json

Imports System.IO



Partial Class _Default

    Inherits System.Web.UI.Page



    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim strTest As String

        strTest = "{""name"":""Peggy"",""email"":""[email protected]""}"



        'Button1.Attributes.Add("onclick", "json(" & strTest & ")")

        Dim mytest As Test

        mytest = FromJosnT(Of Test)(strTest)

        Response.Write(mytest.name & " " & mytest.email)

    End Sub



    Public Function FromJosn(ByVal josn As String) As Object

        Dim ds As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(Test))

        Dim ms As MemoryStream = New MemoryStream(System.Text.Encoding.UTF8.GetBytes(josn))

        Return ds.ReadObject(ms)

    End Function



    Public Function ToJosnT(Of T)(ByVal myT As T) As String

        Dim ds = New DataContractJsonSerializer(GetType(T))

        Dim ms = New MemoryStream()

        ds.WriteObject(ms, myT)



        Dim strReturn As String

        strReturn = Encoding.UTF8.GetString(ms.ToArray())

        ms.Close()

        Return strReturn

    End Function



    Public Function FromJosnT(Of T)(ByVal josn As String) As T

        Dim ds As DataContractJsonSerializer = New DataContractJsonSerializer(GetType(T))

        Dim ms As MemoryStream = New MemoryStream(System.Text.Encoding.UTF8.GetBytes(josn))

        Return ds.ReadObject(ms)

    End Function



    Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click

        Dim myTest As New Test()

        myTest.name = "test"

        myTest.email = "[email protected]"



        Response.Write(ToJosnT(Of Test)(myTest))

    End Sub

End Class





Public Class Test

    Private _name As String

    Public Property name As String

        Get

            Return _name

        End Get

        Set(ByVal value As String)

            _name = value

        End Set

    End Property



    Private _email As String

    Public Property email As String

        Get

            Return _email

        End Get

        Set(ByVal value As String)

            _email = value

        End Set

    End Property

End Class



!!