【发布时间】:2021-05-20 14:01:08
【问题描述】:
背景
我需要在我的项目中添加一个自定义类,以便反序列化和处理 txt 文件中的 json 数据。
这是课程:
Imports Newtonsoft.Json
Public Class ListaGeneral
<JsonProperty("Llave1")>
Public Property Llave1 As String()
<JsonProperty("Cola")>
Public Property Cola As String()
<JsonProperty("Llave2")>
Public Property Llave2 As String()
<JsonProperty("Llave3")>
Public Property Llave3 As String()
<JsonProperty("Llave4")>
Public Property Llave4 As String()
<JsonProperty("Llave5")>
Public Property Llave5 As String()
<JsonProperty("Llave6")>
Public Property Llave6 As String()
End Class
Public Class ListaGeneralRoot
<JsonProperty("ListaGeneral")>
Public Property ListaGeneral As ListaGeneral()
End Class
当我尝试将类添加到我的项目时,它会提示我将其添加到 App_Code 文件夹。添加它并编写我的类属性后,我收到以下错误:
Visual Basic 9.0 does not support auto-implemented properties.
我尝试将我的班级移出 App_Code 文件夹。它不再显示错误,但是我无法使用我的课程。我尝试在我的 aspx 文件代码中初始化一个对象,但找不到它。
我读到这个article 建议我将我的目标框架更改为 4.0,我这样做了,将我的文件移回 App_Code 文件夹,然后我收到了这个错误:
Attribute specifier is not a complete statement. Use a line continuation to apply the attribute to the following statement.
参考这些行:
<JsonProperty("Llave1")>
Public Property Llave1 As String()
我尝试像这样格式化这些行:
<JsonProperty("Llave1")> Public Property Llave1 As String()
我收到一条错误消息:
Property without a 'ReadOnly' or 'WriteOnly' specifier must provide both a 'Get' and a 'Set'.
问题
如何将 getter 和 setter 添加到 JsonProperty?
有人遇到过这个问题吗?这是正确的轨道吗?
将我的目标框架从 v2.0 更改为 4.0 会导致任何问题吗?第一次这样做。
请记住,最终目标是将上面引用的自定义类添加到我的项目中,并能够在我的 aspx 文件中使用它,以便反序列化 txt 文件中的 json 文本。
更新
我试图像这样实现@JohnPete22 的答案:
Imports Newtonsoft.Json
Public Class ListaGeneral
Private _llave1 As String = String.Empty
<JsonProperty("Llave1")> Public Property LLave1 As String
Get
Return _llave1
End Get
Set(value As String)
_llave1 = value
End Set
End Property
'etc etc etc
Sub New()
End Sub
End Class
Public Class ListaGeneralRoot
Private _listageneral As ListaGeneral = Nothing
<JsonProperty("ListaGeneral")> Public Property ListaGeneral As ListaGeneral
Get
If _listageneral Is Nothing Then
_listageneral = New ListaGeneral()
End If
Return _listageneral
End Get
Set(value As ListaGeneral)
_listageneral = value
End Set
End Property
End Class
在尝试测试我的文件后,该文件已经在一个单独的控制台应用程序中使用相同的代码进行了测试并且它可以工作(使用我在原始示例中提到的类的原始实现),我无法获得以下代码工作:
Dim ReceiptsToProcess As ListaGeneralRoot = JsonConvert.DeserializeObject(Of ListaGeneralRoot)(json)
StatusLabel.Text = ReceiptsToProcess.ListaGeneral(0).LLave1(0)
错误:
ListaGeneral has no parameters and its return type cannot be indexed
LLave1 has no parameters and its return type cannot be indexed
我已将文件上传到保管箱:https://www.dropbox.com/s/3kasn11oerrxbuh/20210211.txt?dl=0
如果你可以/愿意测试你的答案。
*我的初始实现在控制台应用程序中工作,但在我的网络应用程序中却没有,这就是这篇文章的重点。
【问题讨论】:
-
您是否尝试过完全声明您的属性?
-
你有没有尝试像这个例子dotnetperls.com/property-vbnet那样添加setter和getter?
-
我不确定我该怎么做。每个属性都是一个 json 数组,可能包含更多的 json 数组。如何编写 getter 和 setter?
-
我想我要的是一个完整的财产声明示例
-
我在一个完全声明的属性示例中包含了一个答案(真的希望它是一个评论)
标签: asp.net json vb.net winforms class