请参阅下面的JSON,我已经使用它进行了验证https://jsonlint.com/:
{
"meta": {
"limit": 3,
"count": 3
},
"data": [{
"id": "1",
"MoreInformation": {
"id2": "22"
},
"type": "Person"
},
{
"id": "2",
"MoreInformation": {
"id2": "42"
},
"type": "Person"
},
{
"id": "3",
"MoreInformation": {
"id2": "99"
},
"type": "Person"
}
]
}
请参阅下面的代码:
Module Module1
Sub Main()
Dim json As String = "{""meta"": {""limit"": 2,""count"": 2},""data"": [{""id"": ""1"",""MoreInformation"": {""id2"": ""22""},""type"": ""Person""},{""id"": ""2"",""MoreInformation"": {""id2"": ""42""},""type"": ""Person""},{""id"": ""3"",""MoreInformation"": {""id2"": ""99""},""type"": ""Person""}]}"
Dim jo As JObject = JObject.Parse(json)
Dim a As JArray = CType(jo("data"), JArray)
Dim list As New List(Of Person)
For Each item In a.Children()
Dim itemProperties = item.Children(Of JProperty)()
Dim person As New Person
person.id1 = itemProperties.FirstOrDefault(Function(x) x.Name = "id")
person.id2 = itemProperties.FirstOrDefault(Function(x) x.Name = "id2")
list.Add(person)
Next
End Sub
End Module
Public Class Person
Public Property id1
Public Property id2
End Class
我希望输出为三个人的列表。
问题出在这条线上:
person.id2 = itemProperties.FirstOrDefault(Function(x) x.Name = "id2")
它总是一无所获。如何使用JSON中的id2填充person.id2?
更新
这项工作:
Sub Main()
Dim json As String = "{""meta"": {""limit"": 2,""count"": 2},""data"": [{""id"": ""1"",""MoreInformation"": {""id2"": ""22""},""type"": ""Person""},{""id"": ""2"",""MoreInformation"": {""id2"": ""42""},""type"": ""Person""},{""id"": ""3"",""MoreInformation"": {""id2"": ""99""},""type"": ""Person""}]}"
Dim jo As JObject = JObject.Parse(json)
Dim a As JArray = CType(jo("data"), JArray)
Dim list As List(Of Person) = JsonConvert.DeserializeObject(Of List(Of Person))(a.ToString)
Console.WriteLine("got here")
End Sub
如果我将类更改为:
Public Class Person
Public Property id
Public Property MoreInformation
End Class
Public Class MoreInformation
Public Property id2
End Class
然而,我仍然不知道如何在我最初的帖子中获得代码。
我不确定这是否是你想要的答案,但我试着像下面的代码一样。
Try
Dim json As String = "{""meta"": {""limit"": 2,""count"": 2},""data"": [{""id"": ""1"",""MoreInformation"": {""id2"": ""22""},""type"": ""Person""},{""id"": ""2"",""MoreInformation"": {""id2"": ""42""},""type"": ""Person""},{""id"": ""3"",""MoreInformation"": {""id2"": ""99""},""type"": ""Person""}]}"
Dim jo As JObject = JObject.Parse(json)
Dim a As JArray = CType(jo("data"), JArray)
Dim list As New List(Of Person)
For Each item In a.Children()
Dim itemProperties = item.Children(Of JProperty)()
Dim itemProperties2 = item.SelectToken("MoreInformation").Children(Of JProperty)()
Dim person As New Person
person.id1 = itemProperties.FirstOrDefault(Function(x) x.Name = "id")
person.id2 = itemProperties2.FirstOrDefault(Function(x) x.Name = "id2")
list.Add(person)
Next
For Each item In list
Debug.WriteLine("id1:" & item.id1.ToString & " id2:" & item.id2.ToString)
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try