我通过asp.net的http帖子收到了以下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"
}
]
}
但这些都没有奏效......
答案 0 :(得分: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
类上使用DataMember
/ Header
,否则反序列化器无法知道REG ID
应该映射到{{1} (因为你不能在VB.Net中使用带空格的成员名称。)
如果您确实希望联系人RegId
,请将DataTable
声明为Data.Contacts
:
DataTable