所以我有一个类,我正在序列化到Json。一切都很顺利,直到这个嵌套类,它给了我一个System.NullReferenceException={"对象引用未设置为对象实例。"}。在编写代码时,intelisense可以识别嵌套类,但显然我在某个地方缺少了一个声明。
根类别:
Public Class RootObject
Private _metadata As List(Of Metadata)
Public Property metadata() As List(Of Metadata)
Get
Return _metadata
End Get
Set(ByVal value As List(Of Metadata))
_metadata = value
End Set
End Property
Private _test_gl As List(Of TestGl)
Public Property test_gl() As List(Of TestGl)
Get
Return _test_gl
End Get
Set(ByVal value As List(Of TestGl))
_test_gl = value
End Set
End Property
End Class
以下是TestGl类的定义:
Public Class TestGl
Private _ref_key_3 As String
<JsonProperty("ref-key-3")> _
Public Property ref_key_3() As String
Get
Return _ref_key_3
End Get
Set(ByVal value As String)
_ref_key_3 = value
End Set
End Property
Private _currency_amount As CurrencyAmount
<JsonProperty("currency-amount")> _
Public Property currency_amount() As CurrencyAmount
Get
Return _currency_amount
End Get
Set(ByVal value As CurrencyAmount)
_currency_amount = value
End Set
End Property
End Class
最后是CurrencyMount类:
Public Class CurrencyAmount
Private _currency As String
<JsonProperty("currency")> _
Public Property currency() As String
Get
Return _currency
End Get
Set(ByVal value As String)
_currency = value
End Set
End Property
Private _amount As String
<JsonProperty("amount")> _
Public Property amount() As String
Get
Return _amount
End Get
Set(ByVal value As String)
_amount = value
End Set
End Property
End Class
下面是用数据填充对象的代码:
Dim Root As RootObject
Dim Meta_Data As New List(Of Metadata)()
Dim Test_Gl As New List(Of TestGl)()
Root = New RootObject
Root.metadata = New List(Of Metadata)()
Root.test_gl = New List(Of TestGl)
Meta_Data = Root.metadata
Test_Gl = Root.test_gl
在这里我给它赋值:
Test_Gl.Add(New AccountGl)
Test_Gl(ItemNo).ref_key_3 = "test"
Test_Gl(ItemNo).currency_amount.currency = "EUR"
Test_Gl(ItemNo).currency_amount.amount = "100"
分配currency_amount.current的行出错了,我已经看了好几个小时了。我看不出来。如有任何意见,我们将不胜感激。
属性是完整的,因为我需要在VS2008中处理这个项目。
我怀疑在需要将_currency_amount
初始化为CurrencyAmount
的新实例的地方,我在任何地方都看不到new CurrencyAmount
。
我怀疑您并不是真的想允许设置currency_aunt属性,否则您应该在底部的示例赋值代码中设置它。如果是这种情况,那么您可能甚至不应该为TestGl
定义Set
成员(它应该是ReadOnly
,它只影响currency_amount
而不影响_currency_amount.currency
(。相反,您应该创建CurrencyAmount
的默认实例,并在构造TestGl
期间将其分配给该字段。这可能很简单,只需将_currency_amount
的声明更改为:
Private _currency_amount As New CurrencyAmount
或者,这可能是您需要与JSON可序列化对象一起使用的解决方案,您保留Set
成员定义,只需在测试代码中添加一行即可在使用前初始化currency_aunt:
Test_Gl(ItemNo).currency_amount = new CurrencyAmount