Search code examples
jsonvb.netjavascriptserializer

Convert vb.net class object to JSON string in vb.net


I am a c# developer and have the requirement to work in vb.net project. I am facing a simple issue I need to convert a class object to json string in vb.net.Problem is when I check the string after conversion I am getting output as:

[{},{},{}]

I am trying to store value of 3 objects into it but I am getting 3 empty objects {}. My code is like this:

Imports System.Web.Script.Serialization

Partial Class test
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim serializer As New JavaScriptSerializer
        Dim msgObj As msg
        Dim loginList As New List(Of msg)()

        msgObj = New msg("mubashir", True)
        loginList.Add(msgObj)
        msgObj = New msg("yasir", False)
        loginList.Add(msgObj)
        msgObj = New msg("umar", True)
        loginList.Add(msgObj)
        Dim s As String = serializer.Serialize(loginList)
        Response.Write(s)

    End Sub
End Class
Public Class msg
    Dim message As String
    Dim status As Boolean
    Sub New(ByRef Messag As String, ByVal Stat As Boolean)



        Me.message = Messag
        Me.status = Stat

    End Sub
End Class

Solution

  • message, status need to declare as Property.

    Public Class msg
          Public Property message() As String
          Public Property status() As Boolean
          Sub New(ByRef Messag As String, ByVal Stat As Boolean)
                Me.message = Messag
                Me.status = Stat    
          End Sub
    End Class