You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET(JSON.NET):如何序列化Controls类并正确赋值?

问题分析与解决

你的问题源于两个方面:类定义的类型错误,以及对数组类型属性的赋值方式理解有误,下面逐一说明并给出修正方案:

1. 类定义的错误点

在frm类中,你将controls属性定义为Control()数组,但Control是.NET自带的控件类,而你自定义的二级结构类名为controls,两者类型不匹配,会导致序列化和赋值时出现问题。

修正后的frm类中controls属性部分:

Public Property controls() As controls()
    Get
        Return m_controls
    End Get
    Set
        m_controls = Value
    End Set
End Property
Private m_controls As controls()

另外注意:你的JSON示例中enabled和mandatory是字符串格式的"TRUE"/"FALSE",但类中定义为Boolean类型,虽然Newtonsoft.Json可以自动转换,但如果需要严格匹配JSON格式,建议将这两个属性的类型改为String:

' 替换controls类中对应属性
Public Property enabled() As String
    Get
        Return m_enabled
    End Get
    Set
        m_enabled = Value
    End Set
End Property
Private m_enabled As String

Public Property mandatory() As String
    Get
        Return m_mandatory
    End Get
    Set
        m_mandatory = Value
    End Set
End Property
Private m_mandatory As String

2. 正确的赋值方式

controls是数组类型,不是单个对象,不能直接通过form.controls.parent访问。需要先创建多个controls实例,再将它们组成数组赋值给form.controls:

完整赋值示例:

Dim form As New frm()

' 主结构赋值
form.form_name = "name"
form.form_text = "text"
form.form_icon = "icon"
form.form_default_button = "default"
form.form_cancel_button = "cancel"
form.form_width = "width"
form.form_height = "height"

' 创建第一个控件实例
Dim labelCtrl As New controls()
labelCtrl.parent = "FORM"
labelCtrl.type = "LABEL"
labelCtrl.name = "LBLUser"
labelCtrl.text = "Buyers Operator ID:"
labelCtrl.align = "LEFT"
labelCtrl.enabled = "TRUE"
labelCtrl.mandatory = ""
labelCtrl.validator = ""
labelCtrl.populate = ""

' 创建第二个控件实例
Dim comboCtrl As New controls()
comboCtrl.parent = "FORM"
comboCtrl.type = "COMBO"
comboCtrl.name = "CBOOperator"
comboCtrl.text = ""
comboCtrl.align = "LEFT"
comboCtrl.tooltip = ""
comboCtrl.enabled = "TRUE"
comboCtrl.mandatory = "TRUE"
comboCtrl.validator = ""
comboCtrl.populate = "SUB"

' 将控件实例组成数组赋值给form.controls
form.controls = New controls() {labelCtrl, comboCtrl}

' 序列化
Dim JSON As String = JsonConvert.SerializeObject(form)

内容的提问来源于stack exchange,提问作者Ray Q

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 15:14:52