Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 856
AaronF Avatar asked Mar 28 '26 21:03

AaronF


1 Answers

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

like image 59
L.B Avatar answered Apr 01 '26 09:04

L.B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!