从C#匿名对象获取属性

Aar*_*onF 3 c# asp.net recursion json anonymous-types

在服务器上,我得到JSON对象。我使用JsonConvert将它们反序列化为匿名对象。然后,我想访问成员,但无法执行以下操作:

object a = jsonObj.something.something.else;
Run Code Online (Sandbox Code Playgroud)

因此,我创建了以下内容,以期能够使用选择器字符串数组访问成员。但是,此处的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);
}
Run Code Online (Sandbox Code Playgroud)

L.B*_*L.B 5

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"]);
Run Code Online (Sandbox Code Playgroud)

要么

string str = (string)jsonObj.SelectToken("prop1.prop2");
Run Code Online (Sandbox Code Playgroud)

2.如果要使用dynamic关键字,则

dynamic jsonObj = JsonConvert.DeserializeObject(json);
Console.WriteLine(jsonObj.prop1.prop2);
Run Code Online (Sandbox Code Playgroud)

两种方式都会打印 abc