Reputation: 21
Good day everyone. I would like to know how is that possible (if is) do such trick (I'm using c# and NewtonSoft JSON library) 1. If I look for a official documentation, there's such example:`
string json = @"{
'Email': 'james@example.com',
'Active': true,
'CreatedDate': '2013-01-20T00:00:00Z',
'Roles': [
'User',
'Admin'
]
}";
Account account = JsonConvert.DeserializeObject<Account>(json);
Console.WriteLine(account.Email);`
I agree, if works. I can find Email
VALUE using Email AS KEY.
2. But how can I find ALL pairs (Key: Value) if I have no idea about KEYs I get? For example, if I have some JSON like:
"1": { "2": "3", "4": "5" }
"a": { "b": "c", "d": "e" }
I can find VALUE if I hardcode KEYS, like:
dynamic JSONOutput = JsonConvert.DeserializeObject(HTMLOutput);
Console.WriteLine(JSONOutput["1"]["2"]); //Output is 3
Console.WriteLine(JSONOutput["1"]["4"]); //Output is 5
Console.WriteLine(JSONOutput["a"]["b"]); //Output is c
Console.WriteLine(JSONOutput["a"]["d"]); //Output is e
But how can I get that keys "1, 2, a, d" etc? Thanx for everyone
Upvotes: 2
Views: 4033
Reputation: 120518
If you parse your JSON as follows:
var jObj = JObject.Parse(jsonString);
you can iterate its properties:
foreach(var kvp in jObj.Cast<KeyValuePair<string,JToken>>().ToList())
{
//kvp.Key
//kvp.Value
}
Upvotes: 3