c# - Parse JSON into an object -
i json string/object server c# client.
this json:
[ {"printid":1,"printref":"00000000-0000-0000-0000-000000000000","header":"header","tc":"tc","companyref":"00000000-0000-0000-0000-000000000000"}, {"printid":2,"printref":"39a10cee-7cb3-4ed3-aec2-293761eed96d","header":"header","tc":"tc","companyref":"00000000-0000-0000-0000-000000000000"}]
i trying convert list of object so:
public ienumerable<model.print> get() { var print = new list<model.print>(); using (var client = new httpclient()) { client.baseaddress = new uri(shared.url); client.defaultrequestheaders.accept.clear(); client.defaultrequestheaders.accept.add(new mediatypewithqualityheadervalue(shared.headertype)); var response = client.getasync(route + "?" + generaltags.customer_ref + "=" + new guid().tostring()).result; if (response.issuccessstatuscode) { var strjson = response.content.readasstringasync().result; var strjson2 = (jobject)jsonconvert.deserializeobject(strjson); list<model.print> items = strjson2["data"].select(x => new model.print { companyref = (guid)x["companyref"], header = (string)x["header"], printid = (int)x["printid"], printref = (guid)x["printref"], tc = (string)x["tc"] }).tolist(); } else { everror(new exception(string.format("{0}: {1}", (int)response.statuscode, response.reasonphrase)), errortags.print_get); } } return print; }
but errors on line:
var strjson2 = (jobject)jsonconvert.deserializeobject(strjson);
this error:
unable cast object of type 'newtonsoft.json.linq.jarray' type 'newtonsoft.json.linq.jobject'.
your top level json structure array instead of object. therefor need cast jarray
instead of jobject
:
var root = (jobject)jsonconvert.deserializeobject(strjson);
if want extract objects instead:
var objs = ((jarray)jsonconvert.deserializeobject(json)).values<jobject>();
Comments
Post a Comment