2

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

Hicks
  • 21
  • 1
  • 2
  • JSON is structured data. You're wanting to treat it like it's unstructured flat data? Why? What's the use case here? What problem are you trying to solve? – mason Jun 13 '17 at 14:11
  • This post I wrote only last night should help you https://stackoverflow.com/questions/44511199/convert-json-string-from-camel-case-to-pascal-case-using-c-sharp/44511499#44511499 – spender Jun 13 '17 at 14:16

1 Answers1

3

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
}
spender
  • 117,338
  • 33
  • 229
  • 351