Parse JSON object in C# using Json.NET

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 2701
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 C# using Json.NET

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Dynamic;

namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{

try
{
var empObj = new List<ExpandoObject>();
var empJSONSource = "{'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'}]}}";
dynamic employeeInfo = JsonConvert.DeserializeObject(empJSONSource);

var countRecord = employeeInfo.Employees.Employee.Count;

for (var i = 0; i < countRecord; i++)
{
dynamic expandoObj = 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);
}

//print the result
foreach (dynamic e in empObj)
{
Console.WriteLine("Employee {0} who is {1} belongs to Department {2}", e.EmployeeName,e.Gender, e.DeptartmentName);
}

Console.ReadKey();
}
catch (Exception ex)
{
throw ex;
}
}
}
}


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

Posted by: Irisp on: 11/20/2017 Level:Starter | Status: [Member] | Points: 10
Nice article and would love to suggest JSON tool which I use to validate JSON data. https://jsonformatter.org

Login to post response