priyanka.sarkar
priyanka.sarkar

Reputation: 26498

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.

Upvotes: 0

Views: 65

Answers (4)

Paarth
Paarth

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

Rafal Wiliński
Rafal Wiliński

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

Dheeraj Kumar
Dheeraj Kumar

Reputation: 4175

You are using Depid instead of Deptid

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

Upvotes: 2

AmanSinghal
AmanSinghal

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

Related Questions