我在 JSON 反序列化后访问动态属性时遇到一些问题。这是 JSON:
{
"user" : {
"511221" :{
"timestamp" : 1403365646384,
"version" : -81317051,
"email" : "user@name.com",
"name" : "My Name",
"structures" : [ "structure.62dd1ff1-f96b-22e3-8d4e-22000c20725r" ]
}
},
}
这里实际上有两个问题。首先是每个用户的“511221”变化。这是在验证时给出的。我无法创建一个用户类,然后创建另一个名称不断变化的类。
此外,它是一个数字。 AFAIK,没有办法将类名作为数字。我在这里有什么选择?我无法控制 API 返回的内容。
因此,我没有反序列化为预定义的类,而是有一个动态的,如下所示:
dynamic jsonObject = JsonConvert.DeserializeObject(response);
我希望能够做到这一点:
string[] structures = jsonObject.user.(authInfo.userid).structures;
换句话说,我希望 (authInfo.userid) 将用户 ID 作为上面的字符串输入,但这似乎不可能。我也试过反射(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;
}
因此可以这样调用它来执行与上面所示相同的操作:
string[] structures = ReflectOnPath(jsonObject, "user." + authInfo.userid + ".structures") as string[];
但是,调用此函数时,类型 (JObject) 上的 GetProperty() 为空。我知道“用户”属性存在,但为什么我不能访问它?
最佳答案
您可以将您的 JSON 反序列化为 JObject
而不是 dynamic
,然后您可以通过属性名称动态访问该属性,例如:
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);
关于c# - JSON反序列化为动态后无法访问属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24357150/