Massey
Massey

Reputation: 1125

How to get a value from JToken at two levels deep in CSharp

I am trying to get the lastName value from a JToken object. The data loaded with JToken and the C# code I have used are given below. The lastName field is within the Person object. I was able to get the values of id and clientId, which are at the top level, without any issue.

JToken loaded data:
{
      "id":"7f9c0978-3baf-0000-0000-0000482f0200",
      "clientId":234123,
      "employeeNumber":282,
      "person":{
         "id":"7f9c0978-3baf-0000-0000-0000482f0200",
         "clientId":143176,
         "firstName":"Brian",
         "middleName":"M",
         "lastName":"Anderson"
    },
       "manager":{
     "managerId": 124,
     "managerFirstName": "Jim",
         "managerLastName": "Jim"
    },
       "workPhone":"4045150315",
       "workEmail":"[email protected]"
}

CSharp code to access lastName field in the person object:

String employeeLastName = employeeData.Children().FirstOrDefault().Value<string>("lastName");

I am getting can't access children data exception.

Upvotes: 0

Views: 974

Answers (1)

Tomas Chabada
Tomas Chabada

Reputation: 3019

You can achieve it with JObject, just like this:

var jObject = JObject.Parse(jsonstring);
var lastName = jObject["person"]["lastName"].Value<string>();

Upvotes: 4

Related Questions