Wednesday, 18 September 2013

reading my json response from a post request i sent

reading my json response from a post request i sent

I made a post request class that I could re-use to make POST requests to
an external api and return the objects they send me (JSON):
class PostRequest
{
private Action<DataUpdateState> Callback;
public PostRequest(string urlPath, string data,
Action<DataUpdateState> callback)
{
Callback = callback;
// form the URI
UriBuilder fullUri = new UriBuilder(urlPath);
fullUri.Query = data;
// initialize a new WebRequest
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(fullUri.Uri);
request.Method = "POST";
// set up the state object for the async request
DataUpdateState dataState = new DataUpdateState();
dataState.AsyncRequest = request;
// start the asynchronous request
request.BeginGetResponse(new AsyncCallback(HandleResponse),
dataState);
}
private void HandleResponse(IAsyncResult asyncResult)
{
// get the state information
DataUpdateState dataState =
(DataUpdateState)asyncResult.AsyncState;
HttpWebRequest dataRequest =
(HttpWebRequest)dataState.AsyncRequest;
// end the async request
dataState.AsyncResponse =
(HttpWebResponse)dataRequest.EndGetResponse(asyncResult);
if (dataState.AsyncResponse.StatusCode.ToString() == "OK")
{
Callback(dataState); // THIS IS THE LINE YOU SHOULD LOOK
AT :)
}
}
}
public class DataUpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
}
the Callback method gets the datastate object and pushes it to this function:
public void LoadDashboard( DataUpdateState dataResponse )
{
Stream response = dataResponse.AsyncResponse.GetResponseStream();
//Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
//StreamReader readStream = new StreamReader(response, encode);
//readStream.Close();
Deployment.Current.Dispatcher.BeginInvoke(() => {
App.RootFrame.Navigate(new Uri("/Interface.xaml",
UriKind.RelativeOrAbsolute));
});
}
I'm now unsure of how to get the body of that reply that has been sent to
me from the API. It is returning a json format, I need to be able to map
it to a nice C# class and use it to display stuff on the phone.
I can't find an example that doesn't use JSON.NET (which doesn't have an
assembly for windows phone 8)

No comments:

Post a Comment