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?
CodePudding user response:
- Read JSON as
JObject
. - Get
users
JObject
from 1. - Convert
JObject
toDictionary<string, object>
and getKeys
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();
Note that the keys contain space in your attached JSON.
CodePudding user response:
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();
CodePudding user response:
Isn't this all you need?
List<string> list = new List<string>();
foreach(var user in keys.users)
{
list.Add(user.toString());
}