【发布时间】:2018-11-05 17:21:00
【问题描述】:
所以我有一个要序列化到 Json 的类。一切顺利,直到这个嵌套类,它给了我一个 System.NullReferenceException = {"Object reference not set to an instance of an object."}。编写代码时,智能感知识别嵌套类,但显然我在某处缺少声明。
根类:
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
最后是 CurrencyAmount 类:
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.currency 的行出错了,我已经看了好几个小时了。我没看到。 任何意见将不胜感激。
属性写得很完整,因为我需要在 VS2008 中处理这个项目。
【问题讨论】:
-
这可能与 JSON 无关。没有序列化部分你能运行程序吗?
-
如果 Test_Gl 是通过反序列化编码字符串创建的,请检查原始 JSON 是否包含货币金额的值。如果没有,您需要在引用它之前赋予它价值,就像@BlueMonkMN 建议的那样