从c#匿名对象获取属性

时间:2014-08-21 16:20:59

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

在服务器上,我获得了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);
}

2 个答案:

答案 0 :(得分:4)

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

答案 1 :(得分:0)

我的代码

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];
相关问题