0

I have a JSON file with the following data:

{ 
  "users": {
    "xyz ": {
      "Name": "abc ",
    },
    "x ": {
      "Name": "xy ",
    },
    "abc": {
      "Name": "ijk",
    },
  }
}

I deserialize the JSON file in C# to a dynamic data type by following code:

dynamic keys = JsonConvert.DeserializeObject(File.ReadAllText(path));

Now I wanna retrieve the name of keys present inside the child of users.

I want the following output:

xyz
x
abc

How can I list the name of the keys?

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
  • 3
    Do you particularly *need* to use dynamic typing here? I'd either parse it as a JObject, or use a class representation with a `Root` class containing a `Dictionary` (where `User` has a `Name` property). – Jon Skeet Jun 29 '22 at 11:53
  • Does this answer your question? [json deserialization to C# with dynamic keys](https://stackoverflow.com/questions/65727513/json-deserialization-to-c-sharp-with-dynamic-keys) – Charlieface Jun 29 '22 at 12:26

2 Answers2

3
  1. Read JSON as JObject.
  2. Get users JObject from 1.
  3. Convert JObject to Dictionary<string, object> and get Keys from the dictionary.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Linq;

JObject obj = JObject.Parse(File.ReadAllText(path));
JObject users = (JObject)obj["users"];
List<string> keys = users.ToObject<Dictionary<string, object>>()
    .Keys
    .ToList();

Sample .NET Fiddle

Note that the keys contain space in your attached JSON.

Yong Shun
  • 35,286
  • 4
  • 24
  • 46
2

you don't need to deserialize to dictionary, to parse is enough

List<string> keys= ((JObject) JObject.Parse(File.ReadAllText(path))["users"])
.Properties().Select(u =>  u.Name).ToList();
Serge
  • 40,935
  • 4
  • 18
  • 45