Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access properties after JSON deserialization into dynamic

I'm having some issues accessing dynamic properties after JSON deserialization. Here is the JSON:

{
  "user" : { 
       "511221" :{ 
        "timestamp" : 1403365646384,
        "version" : -81317051,
        "email" : "[email protected]",
        "name" : "My Name",
        "structures" : [ "structure.62dd1ff1-f96b-22e3-8d4e-22000c20725r" ]
       } 
   },
}

There's actually two problems here. First is that "511221" changes for each user. This is given when authenticating. I can't create a user class and then create another class which name keeps changing.

Also, it's a number. AFAIK, there is no way to have a class name as a number. What are my options here? I cannot control what gets returned by the API.

So instead of deserialization into a predefined class, I have a dynamic, like this:

dynamic jsonObject = JsonConvert.DeserializeObject(response);

I want to be able to do this:

string[] structures = jsonObject.user.(authInfo.userid).structures;

In words, I want (authInfo.userid) to input the user id as a string above, however this does not seem possible. I have also tried reflection:

private static object ReflectOnPath(object o, string path)
{
    object value = o;
    string[] pathComponents = path.Split('.');
    foreach (var component in pathComponents)
    {
        Type type = value.GetType();
        System.Reflection.PropertyInfo pi = type.GetProperty(component);

        //pi is null here, I have no idea why

        value = pi.GetValue(value);
    }
    return value;
}

So it could be called like this to do the same as shown above:

string[] structures = ReflectOnPath(jsonObject, "user." + authInfo.userid + ".structures") as string[];

However, when this is called, GetProperty() on type (JObject) is null. I know the property "user" exists, but why can't I access it?

like image 491
Bailey Stein Avatar asked Jun 23 '14 00:06

Bailey Stein


1 Answers

You can deserialize your JSON to JObject instead of dynamic, then you can access the property by property name dynamically, for example :

JObject jObject = JsonConvert.DeserializeObject<JObject>(response);
var user = "511221";
var structures = jObject["user"][user]["structures"][0];

//given JSON input as in this question, 
//following line will print "structure.62dd1ff1-f96b-22e3-8d4e-22000c20725r"
Console.WriteLine(structures);
like image 93
har07 Avatar answered Sep 22 '22 11:09

har07