问题
i have the following json received through http post in asp.net:
{
"Header": {
"MCC": "415",
"F0": "0",
"REG ID": "0"
},
"Contacts": [
{
"name": "jocelyne",
"mo": "jocelyne"
},
{
"name": "eliane",
"mo": "12345678"
}
]
}
i need to put only the data under contacts in a datatable and deserialize the data under header into 3 variables...
i tried this :
Dim deserializedProduct As List(Of Dictionary(Of String, String)) = JsonConvert.DeserializeObject(Of List(Of Dictionary(Of String, String)))(json)
and this:
Dim table As DataTable = JsonConvert.DeserializeObject(Of DataTable)(json)
i tried using this json:
{
"Data": [
{
"MCC": "415",
"F0": "0",
"REG ID": "0"
}
],
"Contacts": [
{
"name": "jocelyne",
"mo": "jocelyne"
},
{
"name": "eliane",
"mo": "12345678"
}
]
}
but none of these worked...
回答1:
One way is to create some classes that matches the data you recieve:
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
So it's easy to deserialize the data:
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

Now you can easily access the values you're looking for, like data.Header.MCC
etc.
Note that I use the DataContract
/DataMember
here on the Header
class because otherwise the deserializer has no way to know that REG ID
should be mapped to RegId
(since you can't have member names with spaces in VB.Net).
If you really want a DataTable
for your contacts, just declare Data.Contacts
as DataTable
:
Class Data
Public Header As Header
Public Contacts As DataTable
End Class
来源:https://stackoverflow.com/questions/19535504/json-object-into-a-datatable-and-a-string