【发布时间】:2021-02-22 10:12:36
【问题描述】:
我目前有以下:
Dim persons_dr = dt_driverdetails.Select("[B@] = '2' and [PolRef@] = 'YOLX14PC01'")
Dim rss As JObject = New JObject(New JProperty("people"))
For Each row As DataRow In persons_dr
Dim person As person = New person With {
.person_id = row("person_id").ToString,
.email = row("email").ToString,
.mobile = row("mobile").ToString,
.forename = row("forename").ToString,
.surname = row("surname").ToString
}
Dim o As JObject = CType(JToken.FromObject(person), JObject)
rss.Add(New JProperty(o, New JObject()))
Next
people 数组中可以有多个 person 对象。For Each 循环为每个 person 生成一个新的 JObject。我想将它们全部添加到rss JObject 中,这样我的 JObject 最终会像下面的示例:
{
"people": [{
"person_id": "71DLUOBNERUA1002",
"email": "test1@gmail.com",
"mobile": "+4412345678",
"forename": "John",
"surname": "Hopkins"
},
{
"person_id": "71DLUOBNERUA1002",
"email": "test1@gmail.com",
"mobile": "+4412345678",
"forename": "John",
"surname": "Hopkins"
}]
}
但是,我收到一个错误:无法将对象转换为字符串。
我认为这是因为我使用了 JProperty。
任何建议都会很棒 - 最好有人告诉我哪里出了问题,而不是仅仅纠正我的代码 - 渴望学习 :)
更新
Public Class person
Public Property person_id As String
Public Property email As String
Public Property mobile As String
Public Property forename As String
Public Property surname As String
End Class
Public Class people
Public Property persons As List(Of person)
End Class
Private Sub create_person_json()
Dim persons_dr = dt_driverdetails.Select("[B@] = '2' and [PolRef@] = 'YOLX14PC01'")
Dim people As New people
'Dim rss As JObject = New JObject(New JProperty("people"))
For Each row As DataRow In persons_dr
Dim person As person = New person With {
.person_id = row("person_id").ToString,
.email = row("email").ToString,
.mobile = row("mobile").ToString,
.forename = row("forename").ToString,
.surname = row("surname").ToString
}
people.persons.Add(person)
'Dim o As JObject = CType(JToken.FromObject(person), JObject)
Next
End Sub
更新 2
如果我想将另一组 JSON 嵌套到如下列表中:
"people": [{
"person_id": "71DLUOBNERUA1002",
"email": "test1@gmail.com",
"mobile": "+4412345678",
"forename": "John",
"surname": "Hopkins"
"address": {
"line_1": "76 This Place",
"postal_code": "BB11 8DL",
"country": "GB"
},
}]
我可以做以下我的课程吗:
Public Class person
Public Property person_id As String
Public Property email As String
Public Property mobile As String
Public Property forename As String
Public Property surname As String
Public Property address As New address()
Public Property dob As String
'Public Property driverdetails As New driver_details()
End Class
Public Class address
Public Property line_1 As String
Public Property town_city As String
Public Property postal_code As String
Public Property country As String
End Class
那么由于我需要先初始化类而无法将其添加到“person”对象中,我该如何将其添加到现有代码中?
【问题讨论】: