JSON 反序列化为动态后无法访问属性 [英] Cannot access properties after JSON deserialization into dynamic
问题描述
我在 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() 为空.我知道属性user"存在,但为什么我无法访问它?
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屋!