c# - Cannot access properties after JSON deserialization into dynamic -
c# - Cannot access properties after JSON deserialization into dynamic -
i'm having issues accessing dynamic properties after json deserialization. here json:
{ "user" : { "511221" :{ "timestamp" : 1403365646384, "version" : -81317051, "email" : "user@name.com", "name" : "my name", "structures" : [ "structure.62dd1ff1-f96b-22e3-8d4e-22000c20725r" ] } }, } there's 2 problems here. first "511221" changes each user. given when authenticating. can't create user class , create class name keeps changing.
also, it's number. afaik, there no way have class name number. options here? cannot command gets returned api.
so instead of deserialization predefined class, have dynamic, this:
dynamic jsonobject = jsonconvert.deserializeobject(response); i want able this:
string[] structures = jsonobject.user.(authinfo.userid).structures; in words, want (authinfo.userid) input user id string above, not seem possible. have 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 null here, have no thought why value = pi.getvalue(value); } homecoming value; } so called same shown above:
string[] structures = reflectonpath(jsonobject, "user." + authinfo.userid + ".structures") string[]; however, when called, getproperty() on type (jobject) null. know property "user" exists, why can't access it?
you can deserialize json jobject instead of dynamic, can access property property name dynamically, illustration :
jobject jobject = jsonconvert.deserializeobject<jobject>(response); var user = "511221"; var structures = jobject["user"][user]["structures"][0]; //given json input in question, //following line print "structure.62dd1ff1-f96b-22e3-8d4e-22000c20725r" console.writeline(structures); c# json windows-phone-8 reflection json.net
Comments
Post a Comment