0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
priyanka.sarkar
  • 25,766
  • 43
  • 127
  • 173

4 Answers4

2

You are using Depid instead of Deptid

It should be: string DeptId = stuff.Departments.Department[0].Deptid;

Dheeraj Kumar
  • 3,917
  • 8
  • 43
  • 80
  • Apologies, I thought Rafal's answer had already stated that but it looks like he is only talking about the raw JSON. – sr28 Aug 17 '16 at 10:45
  • 2
    Having said that, it looks like he has a typo with stuff.Deparments, where it looks like it should be stuff.Departments ('t' missing). – sr28 Aug 17 '16 at 10:46
1

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;
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Rafal Wiliński
  • 2,240
  • 1
  • 21
  • 26
1

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.

AmanSinghal
  • 2,404
  • 21
  • 22
0

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;
Paarth
  • 580
  • 3
  • 10