user5120455
user5120455

Reputation: 141

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..

Upvotes: 4

Views: 18734

Answers (4)

Nico
Nico

Reputation: 3542

You could first read your Json as a list of dictionaries using Json.NET and then merge them via linq:

var json = @"[
  {
    ""Administrator"": 3
  },
  {
    ""User"": 1
  },
  {
    ""Guest"": 5
  }
]";

var list = JsonConvert.DeserializeObject<List<Dictionary<string, int>>>(json);
var dict = list.SelectMany(d => d).ToDictionary(p => p.Key, p => p.Value);
var adminId = dict["Administrator"];

Upvotes: 2

L.B
L.B

Reputation: 116168

Using Json.Net you can simply do

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

Upvotes: 7

mybirthname
mybirthname

Reputation: 18127

  string json = @"[
  {
    ""Administrator"": 3
  },
  {
    ""User"": 1
  },
  {
    ""Guest"": 5
  }
]";

JArray jsonObject = JsonConvert.DeserializeObject<JArray>(json);

var adminVal = jsonObject[0]["Administrator"].Value<int>();

Like in comments said the JSON is invalid. Here is the fixed version and how to take the Administrator value.

EDIT

Here how to do it without specify the index of the JArray.

var adminObject = jsonObject.Children<JObject>().FirstOrDefault(x=>x.Children<JProperty>().Any(y=>y.Name == "Administrator"));
var adminObjectValue = adminObject.GetValue("Administrator");

Upvotes: 2

Vivek Nuna
Vivek Nuna

Reputation: 1

Your Json should be.

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

You can desrilize this json using NewtonSoft.Json dll to the following class. and get the value of Administrator with class object.

public class ClassName
{
    public int Administrator { get; set; }
    public int? User { get; set; }
    public int? Guest { get; set; }
}

Code to desrialize json to class object.

ClassName obj = JsonConvert.DeserializeObject<ClassName>(json);
//obj.Administrator get or set it according to your requirement.

Upvotes: 1

Related Questions