3

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);
}
AaronF
  • 2,841
  • 3
  • 22
  • 32
  • 2
    `but you can't do something like:...` Why? have you tried to use *dynamic* keyword? – L.B Aug 21 '14 at 16:23
  • you can with dynamics. Look at [this post](http://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Jonesopolis Aug 21 '14 at 16:23
  • I'm new to c#. I haven't heard of this yet. I'll look into it. – AaronF Aug 21 '14 at 16:24
  • dynamic allows for the "." notation access, but can this be used to access using a series of strings? String indexing doesn't work on a dynamic type object, it seems. – AaronF Aug 21 '14 at 16:34

2 Answers2

7

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

L.B
  • 114,136
  • 19
  • 178
  • 224
0

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];
Yitzhak Weinberg
  • 2,324
  • 1
  • 17
  • 21