2016-04-26 133 views
1

我试图去通过每个属性包含在JArray一个dynamic对象:Newtonsoft.Json - 动态对象属性访问

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); 
    } 
} 

当我triy访问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 
    } 
] 

有人能帮助我吗?

+0

您也可以添加您的JSON数据 - 否则每个人都在黑暗中拍摄。 – weismat

+0

我不知道你为什么要在你的循环中再次向上移动树。你想要达到什么目标,并且在prop.GetValue()和prop.GetType()之外? – weismat

回答

2

尝试你的foreach改变

foreach (PropertyDescriptor prop in dynamicProperties) 
{ 
    args[i++] = prop.GetValue(feed); 
} 

UPDATE

args[i++] = feed.GetType().GetProperty(prop.Name).GetValue(feed, null); 

那么,让我们看看它一步一步:

  • feed.GetType():将返回一个类型JArray
  • feed.GetType().GetProperty(prop.Name):问题就在这里,因为
    你试图获得通过名称JArray类型的属性格式,但 prop.Name你的情况将是“digitalInput.field.channel”“digitalInput.field.comment”和“”count(digitalInput.field.comment)“
    因此,它将返回null,因为类型JArray不具有此类属性。
+0

Ooowww!为什么地球上'prop.GetValue(feed)'工作和'feed.GetType()。GetProperty(prop.Name).GetValue(feed,null);'不! – Jordi

+0

你可以给我一个关于这个[post]的帮助吗?(http://stackoverflow.com/questions/36908078/create-a-new-anonymoustype-in​​stance/36908265?noredirect=1#comment61379804_36908265)? – Jordi

+0

@Jordi请参阅我的更新 – Marusyk