asp.net mvc - Error consuming rest API in .net -
i'm trying consume rest api i'm getting next error:
exception details: newtonsoft.json.jsonexception: unexpected json token while reading datatable: startobject
also, if changing endpoint get: system.outofmemoryexception: exception of type 'system.outofmemoryexception' thrown
which pointing line of code:
var table = newtonsoft.json.jsonconvert.deserializeobject<system.data.datatable>(data);
not sure how fix it? can spot error or how fix it?...
thanks..
my controller is:
public async system.threading.tasks.task<actionresult> about() { string url = "https://restcountries.eu/rest/v1/region/africa"; using (system.net.http.httpclient client = new system.net.http.httpclient()) { client.baseaddress = new uri(url); client.defaultrequestheaders.accept.clear(); client.defaultrequestheaders.accept.add(new system.net.http.headers.mediatypewithqualityheadervalue("application/json")); system.net.http.httpresponsemessage response = await client.getasync(url); if (response.issuccessstatuscode) { var data = await response.content.readasstringasync(); var table = newtonsoft.json.jsonconvert.deserializeobject<system.data.datatable>(data); system.web.ui.webcontrols.gridview gview = new system.web.ui.webcontrols.gridview(); gview.datasource = table; gview.databind(); using (system.io.stringwriter sw = new system.io.stringwriter()) { using (system.web.ui.htmltextwriter htw = new system.web.ui.htmltextwriter(sw)) { gview.rendercontrol(htw); viewbag.returneddata = sw.tostring(); } } } } return view();
you shouldn't deserializing datatable
. datatable
generic, in-memory representation of relational data. following deserialization lines of code have:
var data = await response.content.readasstringasync(); var table = newtonsoft.json.jsonconvert.deserializeobject<system.data.datatable>(data);
you asking .net code go grab data internet , turn string of data in-memory representation of relational data, when, @ point, it's string of characters.
you should create model of country properties returned api you're querying.
you can deserialize data , play in .net doing following:
newtonsoft.json.jsonconvert.deserializeobject<ilist<mycountrymodel>>(data);
Comments
Post a Comment