C# Json-动态对象属性访问
我试图遍历C# Json-动态对象属性访问,c#,json.net,C#,Json.net,我试图遍历JArray中包含的dynamic对象上的每个属性: Newtonsoft.Json.Linq.JArray feeds = Newtonsoft.Json.Linq.JArray.Parse(response.Content); if (feeds.Any()) { PropertyDescriptorCollection dynamicProperties = TypeDescriptor.GetProperties(feeds.First()); foreach
JArray
中包含的dynamic
对象上的每个属性:
Newtonsoft.Json.Linq.JArray feeds = Newtonsoft.Json.Linq.JArray.Parse(response.Content);
if (feeds.Any())
{
PropertyDescriptorCollection dynamicProperties = TypeDescriptor.GetProperties(feeds.First());
foreach (dynamic feed in feeds)
{
object[] args = new object[dynamicProperties.Count];
int i = 0;
foreach (PropertyDescriptor prop in dynamicProperties)
{
args[i++] = feed.GetType().GetProperty(prop.Name).GetValue(feed, null);
}
yield return (T)Activator.CreateInstance(typeof(T), args);
}
}
当我尝试访问feed.GetType().GetProperty(prop.Name).GetValue(feed,null)时代码>它告诉我feed.GetType().GetProperty(prop.Name)代码>为空
JSON结构如下所示:
[
{
"digitalInput.field.channel":"tv",
"digitalInput.field.comment":"archive",
"count(digitalInput.field.comment)":130
}
]
有人能帮我吗?试着把你的座位改成
foreach (PropertyDescriptor prop in dynamicProperties)
{
args[i++] = prop.GetValue(feed);
}
更新
args[i++] = feed.GetType().GetProperty(prop.Name).GetValue(feed, null);
所以,让我们一步一步地来看看:
feed.GetType()
:将返回typeJArray
feed.GetType().GetProperty(prop.Name)
:问题就在这里,因为
您试图按名称获取类型为JArray
的属性,但是
prop.Name
在您的情况下将是“digitalInput.field.channel”、“digitalInput.field.comment”和“count(digitalInput.field.comment)”
因此,在结果中,它将返回null
,因为typeJArray
没有这样的属性
您也可以添加JSON数据,否则每个人都会在黑暗中射击。我不知道您为什么要在循环中再次向上移动。在prop.GetValue()和prop.GetType()之外,您到底想要实现什么?Ooowww!究竟为什么prop.GetValue(feed)
feed.GetType().GetProperty(prop.Name).GetValue(feed,null)有效代码>没有!?你能帮我解决这个问题吗?