1

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.

onTheInternet
  • 6,421
  • 10
  • 41
  • 74

3 Answers3

5

Create a class

[DataContract]
public class Response
{
    [DataMember(Name = "error_code")]
    public int ErrorCode { get; set; }

    [DataMember(Name = "access_token")]
    public string AccessToken { get; set; }

    [DataMember(Name = "expires_in")]
    public int ExpiresIn { get; set; }
}

And deserialize your json to strongly typed object:

var json =
    "{\r\n  \"error_code\": 0,\r\n  \"access_token\": \"*******************\",\r\n  \"expires_in\": 7200\r\n}";

var response = JsonConvert.DeserializeObject<Response>(json);
Console.WriteLine(response.AccessToken);
Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
3

If you're doing something as simple as grabbing one value from the JSON you might want to simply:

string thejson = @"{
  ""error_code"": 0,
  ""access_token"": ""*******************"",
  ""expires_in"": 7200
}";

JObject jobj = JObject.Parse(thejson);

string theToken = jobj["access_token"].ToString();
Crowcoder
  • 11,250
  • 3
  • 36
  • 45
1

You could use a dynamic object for a cleaner solution:

string thejson = @"{
""error_code"": 0,
""access_token"": ""*******************"",
""expires_in"": 7200
}";

dynamic data = Json.Decode(thejson);

string theToken = data.access_token;

You will need System.Web.Helpers

AntoOne
  • 99
  • 10