c# - Deserialize JSON string into class with reflection -
i'm trying deserialize json string custom class. have use reflection. have dictionary serialize, send on httpput method, deserialize json string, , read dictionary fields. here's have far:
i'm putting values dictionary this:
dictionary<string, object> valuestoupdate = new dictionary<string, object>(); person p = new person(); p.personname = "origname"; p.age = "25"; p.isalive = true; valuestoupdate.add("person", p); valuestoupdate.add("length", 64.0);
i'm using json serialize this:
string jsonstring = jsonconvert.serializeobject(valuestoupdate);
i take jsonstring , send on rest api put method. put method updates various variables on custom object based on key values in dictionary using reflection (in example i'm updating customobject.person , customobject.length).
the put call deserializes jsonstring this:
dictionary<string, object> newfields = jsonconvert.deserializeobject<dictionary<string, object>>(jsonstring);
i iterate through newfields , want use reflection update customobject's "person" class. httpput method reads jsonstring:
[httpput("/test/stuff")] public string putcontact([frombody]dynamic jsonstring) { dictionary<string, object> newfields = jsonconvert.deserializeobject<dictionary<string, object>>(jsonstring); foreach (var field in newfields) { console.writeline("\nfield key: " + field.key); console.writeline("field value: " + field.value + "\n"); propertyinfo propinfo = typeof(contact).getproperty(field.key); type propertytype = propinfo.propertytype; var value = propinfo.getvalue(contacttoupdate, null); if (propertytype.isclass) { propinfo.setvalue(contacttoupdate, field.value, null); } } }
this generates error:
object of type newtonsoft.json.linq.jobject' cannot converted type 'person';
i've tried using json's populateobject method returned error:
newtonsoft.json.jsonserializationexception: cannot populate json object onto type 'person'. path 'personname', line 1....
so basically, how can go taking json string, converting class (in case 'person' class), , setting customobject's person field reflection?
if (propertytype.isclass) { propinfo.setvalue(contacttoupdate, ((jobject)field.value).toobject(propertytype), null); }
Comments
Post a Comment