Cannot access properties after JSON deserialization into dynamic

别说谁变了你拦得住时间么 提交于 2019-12-19 09:16:23

问题


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

{
  "user" : { 
       "511221" :{ 
        "timestamp" : 1403365646384,
        "version" : -81317051,
        "email" : "user@name.com",
        "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?


回答1:


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


来源:https://stackoverflow.com/questions/24357150/cannot-access-properties-after-json-deserialization-into-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!