嘿,我正在尝试输出多个 JSON 输出值。在 XML 中,它看起来像这样:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<EmployeeInformation>
<EmployeeInfo>
<lastName>Bob</lastName>
<firstName>Barker</firstName>
<eMail>bob_barker@theGameShow.com</eMail>
<badgeID>760013224</badgeID>
</EmployeeInfo>
<EmployeeInfo>
<lastName>John</lastName>
<firstName>Doe</firstName>
<eMail>jDoe@somewhere.com</eMail>
<badgeID>0162000037467</badgeID>
</EmployeeInfo>
</EmployeeInformation>
我想在 JSON 中遵循相同的结构。但是,我目前只得到这个输出:
{
"lastName": "Barker",
"firstName": "Bob",
"eMail": "bob_barker@theGameShow.com",
"badgeID": "760013224",
}{
"lastName": "Doe",
"firstName": "John",
"eMail": "jDoe@somewhere.com",
"badgeID": "0162000037467",
}
从这个代码到这里:
Dim json As String = ""
empInfo.firstName = "Bob"
empInfo.lastName = "Barker"
empInfo.eMail = "bob_barker@theGameShow.com"
empInfo.badgeID = "760013224"
json = JsonConvert.SerializeObject(empInfo, Formatting.Indented)
empInfo.firstName = "John"
empInfo.lastName = "Doe"
empInfo.eMail = "jDoe@somewhere.com"
empInfo.badgeID = "0162000037467"
json &= JsonConvert.SerializeObject(empInfo, Formatting.Indented)
那么,我将如何使用 JSON.net 使其在XML中结构化呢?
您需要将员工对象添加到列表中,然后序列化列表,而不是单独序列化每个员工对象:
Dim employees As New List(Of EmployeeInfo)
Dim empInfo As EmployeeInfo
empInfo = New EmployeeInfo()
empInfo.firstName = "Bob"
empInfo.lastName = "Barker"
empInfo.eMail = "bob_barker@theGameShow.com"
empInfo.badgeID = "760013224"
employees.Add(empInfo)
empInfo = New EmployeeInfo()
empInfo.firstName = "John"
empInfo.lastName = "Doe"
empInfo.eMail = "jDoe@somewhere.com"
empInfo.badgeID = "0162000037467"
employees.Add(empInfo)
Dim json As String = JsonConvert.SerializeObject(employees, Formatting.Indented)
Console.WriteLine(json)
输出:
[
{
"firstName": "Bob",
"lastName": "Barker",
"eMail": "bob_barker@theGameShow.com",
"badgeID": "760013224"
},
{
"firstName": "John",
"lastName": "Doe",
"eMail": "jDoe@somewhere.com",
"badgeID": "0162000037467"
}
]
小提琴:https://dotnetfiddle.net/M2bQqg