JSON反序列化为动态后无法访问属性 [英] Cannot access properties after JSON deserialization into dynamic

查看:76
本文介绍了JSON反序列化为动态后无法访问属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JSON反序列化后访问动态属性时遇到一些问题.这是JSON:

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" ]
       } 
   },
}

这里实际上有两个问题.首先是"511221"随每个用户而变化.认证时给出.我无法创建一个用户类,然后再创建另一个名称不断变化的类.

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.

也是一个数字. AFAIK,无法将类名作为数字.我在这里有什么选择?我无法控制API返回的内容.

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;

换句话说,我想(authInfo.userid)在上面的字符串中输入用户ID,但这似乎是不可能的.我也尝试过反思:

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

但是,当调用此函数时,类型(JObject)上的GetProperty()为空.我知道属性用户"存在,但是为什么我不能访问它?

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

推荐答案

您可以将JSON反序列化为JObject而不是dynamic,然后可以按属性名称动态访问属性,例如:

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

这篇关于JSON反序列化为动态后无法访问属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆