priyanka.sarkar priyanka.sarkar - 3 months ago 6
JSON Question

Not able to parse JSON data properly

I have a JSON as below

var source = "{'Departments': {'Department': [{'DeptName': 'HR','Deptid': '9228590'},{'DeptName': 'Finance','Deptid': '9295426' }]}}";


I need to get all the
Deptid
and
DeptName


I am using Newtonsoft.Json and tried as under

using Newtonsoft.Json;
using System;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
GetInformation();
}

private static void GetInformation()
{
try
{
var source = "{'Departments': {'Department': [{'DeptName': 'HR','Deptid': '9228590'},{'DeptName': 'Finance','Deptid': '9295426' }]}}";
dynamic stuff = JsonConvert.DeserializeObject(source);

string DeptId = stuff.Deparments.Department[0].Deptid;
string DeptName = stuff.Deparments.Department[0].DeptName;
}
catch (Exception ex)
{
throw ex;
}
}
}
}


But I am getting Null Reference exception.

Please help

Answer

Your object does not have property DeptId, only Depid. Also, these properties are nested so I guess you need to use something like this:

string DeptId = stuff.Departments.Department[0].Depid;
string DeptName = stuff.Departments.Department[0].DeptName;