在 vb.net 中将 vb.net 类对象转换为 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30186520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 19:07:01  来源:igfitidea点击:

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

jsonvb.netjsonserializer

提问by killer

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:

我是 ac# 开发人员,需要在 vb.net 项目中工作。我面临一个简单的问题,我需要在 vb.net.Problem 中将类对象转换为 json 字符串,当我在转换后检查字符串时,我得到的输出为:

[{},{},{}]

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

我试图将 3 个对象的值存储到其中,但我得到了 3 个空对象 {}。我的代码是这样的:

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

回答by Nguyen Kien

message, statusneed to declare as Property.

messagestatus需要声明为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

回答by Pondidum

It looks like it's your msgclass at fault here, as you have declared two fields rather than two properties:

看起来这是你的msg类有错,因为你已经声明了两个字段而不是两个属性:

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