2016-04-26 129 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