c#如何获取动态对象中的第n个对象属性名



我正在尝试枚举JSON反序列化对象的属性名称。

dynamic x = data.elements[i];
Console.Write(x);
{{
"order_type": "request",
"order_id": "A511",
"order_Date" : null,
"order_name": "Preston",
}}

.GetProperties()将返回以下内容:

Console.Write(x.GetType().GetProperties())
[0]: {Newtonsoft.Json.Linq.JTokenType Type}
[1]: {Newtonsoft.Json.Linq.JToken Item [System.Object]}
[2]: {Newtonsoft.Json.Linq.JToken Item [System.String]}
[3]: {Boolean HasValues}
[4]: {Newtonsoft.Json.Linq.JToken First}
[5]: {Newtonsoft.Json.Linq.JToken Last}
[6]: {Int32 Count}
[7]: {Newtonsoft.Json.Linq.JContainer Parent}
[8]: {Newtonsoft.Json.Linq.JToken Root}
[9]: {Newtonsoft.Json.Linq.JToken Next}
[10]: {Newtonsoft.Json.Linq.JToken Previous}
[11]: {System.String Path}

有"First"one_answers"Last"。它有"Next";和";Previous"。它甚至有"Parent"。

但是我需要"n"的名称。财产。例如,我需要一个对order_date的引用。来获取它的名称。

这里的目标是用空字符串"代替null。但我需要一种方法来确定null属性的名称

如果我完全错了,而且有更好的方法,我愿意接受纠正。

您可以像Charlie的注释中提到的那样执行Where,但是如果您需要迭代属性,这是一种方法。

public void DoWork()
{
string jsonString = @"
{
""order_type"": ""request"",
""order_id"": ""A511"",
""order_Date"" : null,
""order_name"": ""Preston"",
}
";
JObject jObject = JObject.Parse(jsonString);
foreach (KeyValuePair<string, JToken> pair in jObject)
{
string keyName = pair.Key;
Console.WriteLine(keyName);
}
}

首先,我想清楚了:

TypeDescriptor.GetProperties(data.elements[i])[2].Name; // --> "order_date"

那么,现在我可以for()每一个并检查是否为空

接受其他/更好的解决方案。

只是使用LINQProperties

x.Properties.Where(j => j.Type == JTokenType.Null)

最新更新