0

Hey all I am trying to output more than one JSON output value. In XML it would look like this:

<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<EmployeeInformation>
  <EmployeeInfo>
    <lastName>Bob</lastName>
    <firstName>Barker</firstName>
    <eMail>[email protected]</eMail>
    <badgeID>760013224</badgeID>
  </EmployeeInfo>
  <EmployeeInfo>
    <lastName>John</lastName>
    <firstName>Doe</firstName>
    <eMail>[email protected]</eMail>
    <badgeID>0162000037467</badgeID>
  </EmployeeInfo>
</EmployeeInformation>

I would like to follow that same structure in JSON. However, I currently only am getting this output:

{
  "lastName": "Barker",
  "firstName": "Bob",
  "eMail": "[email protected]",
  "badgeID": "760013224",
}{
  "lastName": "Doe",
  "firstName": "John",
  "eMail": "[email protected]",
  "badgeID": "0162000037467",
}

From this code here:

Dim json As String = ""

empInfo.firstName = "Bob"
empInfo.lastName = "Barker"
empInfo.eMail = "[email protected]"
empInfo.badgeID = "760013224"

json = JsonConvert.SerializeObject(empInfo, Formatting.Indented)

empInfo.firstName = "John"
empInfo.lastName = "Doe"
empInfo.eMail = "[email protected]"
empInfo.badgeID = "0162000037467"

json &= JsonConvert.SerializeObject(empInfo, Formatting.Indented)

So how would I go about making it structured as it is in XML using JSON.net?

1 Answer 1

2

Instead of serializing each employee object individually, you need to add your employee objects to a list and then serialize the list:

Dim employees As New List(Of EmployeeInfo)
Dim empInfo As EmployeeInfo

empInfo = New EmployeeInfo()
empInfo.firstName = "Bob"
empInfo.lastName = "Barker"
empInfo.eMail = "[email protected]"
empInfo.badgeID = "760013224"
employees.Add(empInfo)

empInfo = New EmployeeInfo()
empInfo.firstName = "John"
empInfo.lastName = "Doe"
empInfo.eMail = "[email protected]"
empInfo.badgeID = "0162000037467"
employees.Add(empInfo)

Dim json As String = JsonConvert.SerializeObject(employees, Formatting.Indented)
Console.WriteLine(json)

Output:

[
  {
    "firstName": "Bob",
    "lastName": "Barker",
    "eMail": "[email protected]",
    "badgeID": "760013224"
  },
  {
    "firstName": "John",
    "lastName": "Doe",
    "eMail": "[email protected]",
    "badgeID": "0162000037467"
  }
]

Fiddle: https://dotnetfiddle.net/M2bQqg

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.