Reputation: 141
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
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
Reputation: 116168
Using Json.Net you can simply do
int value = (int)JArray.Parse(json).Children()["Administrator"].First();
Upvotes: 7
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
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