【问题标题】:Getting property from c# anonymous object从 c# 匿名对象获取属性
【发布时间】:2014-10-15 08:59:08
【问题描述】:

在服务器上,我得到 JSON 对象。我使用 JsonConvert 将它们反序列化为匿名对象。然后我想访问成员,但我不能这样做:

object a = jsonObj.something.something.else;

所以我创建了以下内容,目的是能够使用选择器字符串数组访问成员。但是,这里的 getProperty() 总是返回 null。有什么想法吗?

private object recGetProperty(object currentNode, string[] selectors, int index) {
    try {
        Type nodeType = currentNode.GetType();
        object nextNode = nodeType.GetProperty(selectors[index]);
        if (index == (selectors.Length - 1)) {
            return nextNode;
        }
        else {
            return recGetProperty(nextNode, selectors, index + 1);
        }
    }
    catch (Exception e) {
        return null;
    }           
}

private object getProperty(object root, string[] selectors) {
    return recGetProperty(root, selectors, 0);
}

【问题讨论】:

  • but you can't do something like:... 为什么?你试过用dynamic关键字吗?
  • 你可以用动态。看this post
  • 我是 C# 新手。我还没听说过这个。我会调查的。
  • 动态允许“.”符号访问,但这可以用于使用一系列字符串进行访问吗?字符串索引似乎不适用于动态类型对象。

标签: c# asp.net json recursion anonymous-types


【解决方案1】:

JsonConvert.DeserializeObject 不会反序列化为匿名对象(我猜,你不使用 JsonConvert.DeserializeAnonymousType)。根据 json,它返回 JObjectJArray

1.由于JObject实现了IDictionary<string, JToken>,你可以这样使用它

string json = @"{prop1:{prop2:""abc""}}";

JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
Console.WriteLine(jsonObj["prop1"]["prop2"]);

string str = (string)jsonObj.SelectToken("prop1.prop2");

2.如果要使用动态关键字,那么

dynamic jsonObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.prop1.prop2);

两种方式都会打印abc

【讨论】:

    【解决方案2】:

    我的代码

    Dictionary<string, object> dictionaryObject = new Dictionary<string, object>();
            if (anonymousObject is string)
            {
                dictionaryObject = JsonConvert.DeserializeObject<Dictionary<string,object>>((string)anonymousObject);
            }
            if (!dictionaryObject.ContainsKey(propertyName))
            {
                throw new Exception($"property name '{propertyName}' not found");
            }
            object value = dictionaryObject[propertyName];
    

    【讨论】:

      猜你喜欢
      • 2016-12-31
      • 1970-01-01
      • 2011-04-09
      • 2015-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-05
      相关资源
      最近更新 更多