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?
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With