我这样做是为了将JSON格式的字符串转换为VB.NET Object。
我找不到为什么它不起作用!
jsonSettingsWrapper.vb
Public Class jsonSettingsWrapper
'Public setting As jsonSettings
Public Property setting As jsonSettings
Get
Return m_setting
End Get
Set(value As jsonSettings)
m_setting = value
End Set
End Property
Private m_setting As jsonSettings
End Class
Public Class jsonSettings
Public Property root_folder_path As String
Get
Return m_root_folder_path
End Get
Set(value As String)
m_root_folder_path = value
End Set
End Property
Private m_root_folder_path As String
Public Property ignored_files As String()
Get
Return m_ignored_files
End Get
Set(value As String())
m_ignored_files = value
End Set
End Property
Private m_ignored_files As String()
Public Property last_pack_date As String
Get
Return m_last_pack_date
End Get
Set(value As String)
m_last_pack_date = value
End Set
End Property
Private m_last_pack_date As String
Public Property last_push_date As String
Get
Return m_last_push_date
End Get
Set(value As String)
m_last_push_date = value
End Set
End Property
Private m_last_push_date As String
Public Property no_of_packs As Integer
Get
Return m_no_of_packs
End Get
Set(value As Integer)
m_no_of_packs = value
End Set
End Property
Private m_no_of_packs As Integer
Public Property packs_array As packs()
Get
Return m_packs_array
End Get
Set(value As packs())
m_packs_array = value
End Set
End Property
Private m_packs_array As packs()
End Class
Public Class packs
Public Property filename As String
Get
Return m_filename
End Get
Set(value As String)
m_filename = value
End Set
End Property
Private m_filename As String
Public Property pack_date As String
Get
Return m_pack_date
End Get
Set(value As String)
m_pack_date = value
End Set
End Property
Private m_pack_date As String
End Class
Form1.vb的
Imports System.Web.Script.Serialization
Imports WindowsApplication1.jsonSettingsWrapper
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim ser As New JavaScriptSerializer
Dim settingsString As String = IO.File.ReadAllText("settings.json")
MsgBox(settingsString)
Dim settings = ser.Deserialize(Of jsonSettingsWrapper)(settingsString)
MsgBox(settings.setting) 'empty
MsgBox(settings.setting.root_folder_path)
' ^ ^ Error: A first chance exception of type 'System.NullReferenceException' occurred in FilesSync.exe
End Sub
如代码注释中所述,当它尝试访问其某些值时会发生错误。任何人都可以说明为什么会发生这种情况。我在哪里做错了?
编辑:我使用的JSON是:
{"settings": {
"root_folder_path": "ab",
"ignored_files": [
"cd",
"ef"
],
"last_pack_date": "12",
"last_push_date": "21",
"no_of_packs": 3,
"packs_array": [
{
"filename": "aa",
"pack_date": "21"
}
]
}}
答案 0 :(得分:0)
您的JSON使用属性名称"设置"但是你的班级使用"设置&#34 ;,改变你的班级以使用正确的名字
Public Class jsonSettingsWrapper
'Public setting As jsonSettings
Public Property settings() As jsonSettings
Get
Return m_setting
End Get
Set(ByVal value As jsonSettings)
m_setting = value
End Set
End Property
Private m_setting As jsonSettings
End Class
或使用DataContract