【问题标题】:Newtonsoft.Json - Dynamic object property accessNewtonsoft.Json - 动态对象属性访问
【发布时间】:2016-04-26 15:53:35
【问题描述】:

我正在尝试检查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
    }
]

有人可以帮我吗?

【问题讨论】:

  • 你也可以添加你的 JSON 数据 - 否则每个人都在黑暗中射击。
  • 我不知道你为什么要在你的循环中再次向上移动树。你到底想实现什么并且在 prop.GetValue() 和 prop.GetType() 之外?

标签: c# json.net


【解决方案1】:

尝试将你的 foreach 更改为

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

更新

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 没有此类属性。

【讨论】:

  • 哇哦!为什么prop.GetValue(feed) 有效而feed.GetType().GetProperty(prop.Name).GetValue(feed, null); 无效!?
  • 你能帮我解决一下这个post吗?
猜你喜欢
  • 2011-08-10
  • 2013-07-21
  • 2011-06-15
  • 2019-01-29
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
  • 2021-10-25
相关资源
最近更新 更多