1

我通过asp.net中的http post收到了以下json:

 {
"Header": {
    "MCC": "415",
    "F0": "0",
    "REG ID": "0" 
},
"Contacts": [
    {
        "name": "jocelyne",
        "mo": "jocelyne"
    },
    {
        "name": "eliane",
        "mo": "12345678"
    }
]
}

我只需要将联系人下的数据放在数据表中,并将标题下的数据反序列化为 3 个变量...

我试过这个:

 Dim deserializedProduct As List(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(Of List(Of Dictionary(Of String, String)))(json)

和这个:

Dim table As DataTable = JsonConvert.DeserializeObject(Of DataTable)(json)

我尝试使用这个json:

 {
"Data": [
    {
        "MCC": "415",
        "F0": "0",
        "REG ID": "0"
    }
],
"Contacts": [
    {
        "name": "jocelyne",
        "mo": "jocelyne"
    },
    {
        "name": "eliane",
        "mo": "12345678"
    }
]
}

但这些都不起作用......

4

1 回答 1

1

一种方法是创建一些与您收到的数据匹配的类:

Class Data
    Public Header As Header
    Public Contacts As List(Of Contact)
End Class

<System.Runtime.Serialization.DataContract>
Class Header
    <System.Runtime.Serialization.DataMember(Name := "MCC")>
    Public MCC As Integer
    <System.Runtime.Serialization.DataMember(Name := "F0")>
    Public F0 As Integer
    <System.Runtime.Serialization.DataMember(Name := "REG ID")>
    Public RegId As Integer
End Class

Class Contact
    Public Name As String
    Public Mo As String
End Class

所以很容易反序列化数据:

Sub Main
    Dim json As String = <json>
                        {
                        "Header": {
                            "MCC": "415",
                            "F0": "0",
                            "REG ID": "0"
                        },
                        "Contacts": [
                            {
                                "name": "jocelyne",
                                "mo": "jocelyne"
                            },
                            {
                                "name": "eliane",
                                "mo": "12345678"
                            }
                        ]
                        }</json>.Value


    Dim data As Data = JsonConvert.DeserializeObject(Of Data)(json)
    data.Dump()
End Sub

在此处输入图像描述

现在您可以轻松访问您正在寻找的值,例如data.Header.MCC等。

请注意,我在类上使用了DataContract/ ,否则反序列化器无法知道应该映射到哪个(因为在 VB.Net 中不能有带空格的成员名称)。DataMemberHeaderREG IDRegId

如果您真的想要一个DataTable联系人,只需声明Data.ContactsDataTable

Class Data
    Public Header As Header
    Public Contacts As DataTable
End Class
于 2013-10-23T08:00:47.830 回答