vb.net序列化集合无法将对象添加到对象?

时间:2017-07-22 18:11:58

标签: json vb.net

我正在尝试生成一些看起来像这样的JSON:

{
"@type": "MessageCard",
"sections": [
    {
    "activityTitle": " Request",
        "facts": [
        {
                "name": "name1",
                "value": "Value"
            },
            {
                "name": " Date:",
                "value": "Value Date"
            }
        ],
    "text": "Some Test."
    }
 ],
"potentialAction": [
    {
        "@type": "ActionCard",
        "name": "Add a comment",
        "inputs": [
            {
                "@type": "TextInput",
                "id": "comment",
                "isMultiline": true
            }
         ]
     }
   ]
}

我在VS中执行了一个特殊粘贴,它为我生成了类结构:

Public Class MessageCard
 Public Property type As String
 Public Property context As String
 Public Property summary As String
 Public Property themeColor As String
 Public Property sections() As Section
 Public Property potentialAction() As Potentialaction
End Class

我正在尝试将这些部分添加到对象中:

Dim m as New MessageCard  
Dim s As New List(Of Section)
        s.Add(s1)
        s.Add(s2)
        m.sections = s

编译器抱怨它无法将Sections列表转换为Section。该类是否生成错误,或者我是否错误地构建了它?

1 个答案:

答案 0 :(得分:0)

首先,您的JSON不完整,您展示的类不会创建该JSON。

发布时,JSON只显示SectionspotentialAction类,它们之间没有任何关联。需要附上[ ... ]来表示包含其中两个的MessageCard类。

  

[{
    " @ type":" MessageCard",
    ...
  }]

接下来,您所拥有的课程会显示JSON中不存在的各种内容:contextsummarythemeColor。我认为这些可能因为简洁而缺失,但令人困惑。还有其他两种类型缺少,JSON中的 FactInput

更正了,课程应为:

Public Class MsgCard
    <JsonProperty("@type")>
    Public Property ItemType As String
    Public Property sections As List(Of Section)
    Public Property potentialAction As List(Of Potentialaction)

    Public Sub New()
        sections = New List(Of Section)
        potentialAction = New List(Of Potentialaction)
    End Sub
End Class

Public Class Section
    Public Property activityTitle As String
    Public Property facts As Fact()
    Public Property text As String
End Class

Public Class Fact
    Public Property name As String
    Public Property value As String
End Class

Public Class Potentialaction
    <JsonProperty("@type")>
    Public Property ActionType As String
    Public Property name As String
    Public Property inputs As Input()
End Class

Public Class Input
    <JsonProperty("@type")>
    Public Property InputType As String
    Public Property id As String
    Public Property isMultiline As Boolean
End Class

注释

  • 您没有指定JSON序列化程序,因此按照Microsoft的建议准备好JSON.NET。
  • @type是非法的属性名称,因此JsonProperty属性用于创建别名。我还使用了较少混乱的冗余名称。
  • 如果您要创建并将其推送到类对象中,则可能需要将FactInput更改为List(Of T)

最后,对于您提出的实际问题,大多数自动类生成器都有阵列问题(甚至是VS)。

Public Property sections() As Section
' should be:
Public Property sections As Section()

这只是声明sections将是一个数组,它不会创建数组。通常这不是问题,因为Serializer / Deserializer将创建数组。要允许类外部的代码添加到它们中,您可能希望使用List作为上面的类,然后在构造函数中创建实例:

Public Sub New()
    sections = New List(Of Section)
    potentialAction = New List(Of Potentialaction)
End Sub