简体   繁体   中英

Getting property from c# anonymous object

On a server, I get JSON objects. I use JsonConvert to deserialize them into anonymous objects. I then want to access the members, but I can't do something like:

object a = jsonObj.something.something.else;

So I created the following, with the intention of being able to access a member using an array of selector strings. However, getProperty() here always returns null. Any ideas?

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);
}

JsonConvert.DeserializeObject does not deserialize to anonymous object (I guess, you don't use JsonConvert.DeserializeAnonymousType ). Depending on json it returns either JObject or JArray .

1. Since JObject implements IDictionary<string, JToken> you can use it this way

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

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

or

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

2. If you want to use the dynamic keyword, then

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

Both ways will print abc

my code

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM