0

I have the below JSON which I have parsed into JToken 'token'.

{
  "base": {
    "employees": {
      "employeewage": {
        "employeeids": [
          {
            "employeeid": "AA",
            "details": [
              {
                "position": "Tester",
                "salary": 8500,
                "currency": "INR"
              }
            ]
          }
        ]
      }
    }
  }
}

I need to get the value of 'salary' field alone. The code I tried,

var salary = token.SelectToken("$.base.employees.employeewage.employeeids.details.salary").ToString();

I am getting exception with this. Any help would be helpful.

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
Black Pearl
  • 79
  • 1
  • 2
  • 9
  • The easiest way is to deserialize it to a complete C# object, and then just choose the fields you want from the C# object. See [here](https://stackoverflow.com/questions/50480417/accessing-a-single-value-from-a-json-file-in-c-sharp). – Robert Harvey May 26 '20 at 15:01
  • You should access it as an array – Pavel Anikhouski May 26 '20 at 15:01
  • You should add exception if you have one) – Guru Stron May 26 '20 at 15:01
  • Not an explicit answer to your question, but if you create a class and use this custom deserializer, then you should accomplish what you want: – David P May 26 '20 at 15:02
  • https://stackoverflow.com/questions/33088462/can-i-specify-a-path-in-an-attribute-to-map-a-property-in-my-class-to-a-child-pr – David P May 26 '20 at 15:03

2 Answers2

2

employeeids and details are an arrays, so you should reflect it and enumerate them after parsing

var json = JObject.Parse(jsonString);
var employees = json["base"]?["employees"]?["employeewage"]?["employeeids"];

foreach (var detail in employees.SelectMany(e => e["details"]))
{
    var salary = detail["salary"]?.Value<string>();
}

Or get the first item of all details from all employees

var salary = employees.SelectMany(e => e["details"]).FirstOrDefault()?["salary"]?.Value<string>();
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
2

As @Pavel Anikhouski said in the comments you have arrays (employeeids and details) in your json, so you need to add array handling to the path:

var x= @"{
  'base': {
    'employees': {
            'employeewage': {
                'employeeids': [
                  {
            'employeeid': 'AA',
                    'details': [
                      {
                'position': 'Tester',
                        'salary': 8500,
                        'currency': 'INR'
              }
            ]
          }
        ]
      }
    }
  }
}";

var salary = JToken.Parse(x)
    .SelectToken("$.base.employees.employeewage.employeeids[0].details[0].salary")
    .ToString();

Also see examples in the Newtonsoft docs.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132