我正在使用C#和Json.NET.如果我有一个JObject,我想要一个对象内的键列表,类似于object.Keys()
返回对象中的键的方式.这似乎很明显,但我很难找到一种方法来做到这一点.
编辑: 我正在遍历对象,我想在我经历时吐出对象中的所有键.我意识到这个例子会导致多次看到相同的密钥,这对我的需求是可以的.
public void SomeMethod(JObject parent) {
foreach (JObject child in parent.Children()) {
if (child.HasValues) {
//
// Code to get the keys here
//
SomeMethod(child);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*ing 129
IList<string> keys = parent.Properties().Select(p => p.Name).ToList();
Run Code Online (Sandbox Code Playgroud)
Bla*_*g23 18
从将JSON.NET JObject的属性/标记转换为字典键
您可以简单地将其JObject
转换为Dictionary对象并Keys()
从Dictionary对象访问该方法.
像这样:
using Newtonsoft.Json.Linq;
//jsonString is your JSON-formatted string
JObject jsonObj = JObject.Parse(jsonString);
Dictionary<string, string> dictObj = jsonObj.ToObject<Dictionary<string, string>>();
Run Code Online (Sandbox Code Playgroud)
您现在可以通过该dictObj.Keys()
方法访问这些键.您也可以通过执行来查看密钥是否存在dictObj.ContainsKey(keyName)
.
显然,您可以根据需要设置字典格式(可以是Dictionary<string, object>
等).
归档时间: |
|
查看次数: |
62163 次 |
最近记录: |