Reputation: 26498
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.
Upvotes: 0
Views: 65
Reputation: 590
Actually you are using wrong names for Objects
like Departments, Depid
. IF you correct this objects
name it will work.
string DeptId = stuff.Departments.Department[0].Deptid;
string DeptName = stuff.Departments.Department[0].DeptName;
Upvotes: 0
Reputation: 2390
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;
Upvotes: 1
Reputation: 4175
You are using Depid instead of Deptid
It should be: string DeptId = stuff.Departments.Department[0].Deptid;
Upvotes: 2
Reputation: 2504
Try this
stuff.Departments.Department[0].DeptName
stuff.Departments.Department[0].Depid
This is just an example to get the first element from the Array. You need to iterate over array to get the name and id for all the objects in the Array.
Upvotes: 1