Parse JSON object in VB.net using Json.NET

Rajnilari2015
Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 7531
Suppose we have a JSON as under

{
"Employees": {
"Employee": [
{
"DeptName": "Software",
"EmployeeName": "Niladri",
"Gender":"Male"
},
{
"DeptName": "Finance",
"EmployeeName": "Arina",
"Gender":"Female"
},
{
"DeptName": "Doctor",
"EmployeeName": "Babai",
"Gender":"Female"
},
{
"DeptName": "Article Authors",
"EmployeeName": "RNA Team",
"Gender":"Male"
}
]
}
}


The objective is to parse the JSON in VB.net using Json.NET

Imports Newtonsoft.Json
Imports System.Collections.Generic
Imports System.Dynamic

Namespace ConsoleApplication
Class Program
Private Shared Sub Main(args As String())

Try
Dim empObj = New List(Of ExpandoObject)()
Dim source = "{'Employees': {'Employee': [{'DeptName':'Software','EmployeeName':'Niladri','Gender':'Male'},{'DeptName':'Finance','EmployeeName':'Arina','Gender':'Female'}, {'DeptName': 'Doctor','EmployeeName': 'Babai','Gender':'Female'},{'DeptName':'Article Authors','EmployeeName': 'RNA Team','Gender':'Male'}]}}"
Dim employeeInfo As dynamic = JsonConvert.DeserializeObject(source)

Dim countRecord = employeeInfo.Employees.Employee.Count

For i As var = 0 To countRecord - 1
Dim expandoObj As dynamic = New ExpandoObject()
expandoObj.EmployeeName = Convert.ToString(employeeInfo.Employees.Employee(i).EmployeeName)
expandoObj.DeptartmentName = Convert.ToString(employeeInfo.Employees.Employee(i).DeptName)
expandoObj.Gender = Convert.ToString(employeeInfo.Employees.Employee(i).Gender)
empObj.Add(expandoObj)
Next

'print the result
For Each e As dynamic In empObj
Console.WriteLine("Employee {0} who is {1} belongs to Department {2}", e.EmployeeName, e.Gender, e.DeptartmentName)
Next

Console.ReadKey()
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
End Namespace


We are converting the empJSONSource string into an object by using the JsonConvert.DeserializeObject method, then looping through the record count and preparing the List<ExpandoObject>. Finally by using a Foreach Loop, we are looping through teh collection and displaying the records.

Comments or Responses

Login to post response