Search code examples
c#jsonjson.netjson-deserialization

How to get element by key in JSON array


I have the following JArray object (newtonsoft.json)

[
  {
    "Administrator": 3
  },
  {
    "User": 1
  },
  {
    "Guest": 5
  }
]

How do I retrieve the value (3) for key "Administrator" ? It's asking me for an array index but I would like to retrieve by key.. as this list can expand and contract..


Solution

  • Using Json.Net you can simply do

    int value = (int)JArray.Parse(json).Children()["Administrator"].First();