I have some C# code that makes an HTTP web request to grab an access token. The object comes back in the following format:
{
"error_code": 0,
"access_token": "*******************",
"expires_in": 7200
}
I am currently setting the request to a string object and trimming it. But this seems brittle and prone fo failure. I'd like to just grab the token like this.
string myToken = httpWebResponse.access_token
So I started looking into Json.NET after seeing this stack overflow post.
Parsing Json rest api response in C#
Which is exactly what I want to do. However, I can't seem to follow his accepted answer because his response object has a title ("response") whereas mine does not.
I decided to look to the documentation to find an answer and I came up short there too. https://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm
His response has a title, in this case, "results".
Here is my C# code.
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + appId + "&secret=" + secret);
request.Method = "GET";
request.KeepAlive = false;
request.ContentType = "appication/json";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
/*
JSON Parse Attempt
JObject joResponse = JObject.Parse(response.ToString());
JArray array = (JArray)joResponse[""];
int id = Convert.ToInt32(array[0].ToString());
*/
//////////////////////////
string myResponse = "";
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream()))
{
myResponse = sr.ReadToEnd();
}
return myResponse;
}
catch (Exception e)
{
return e.ToString();
}
But I only get an error when I uncomment the parsing lines.
Any help will be appreciate.