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.

6
  • Why not just deserialize into a custom class with the 3 properties? Commented Oct 17, 2018 at 15:55
  • 1
    You don't have an array, just use the JObject. Commented Oct 17, 2018 at 15:56
  • @maccettura Because I'm a c# noob who doesn't know how. When I googled how to do this I kept getting directed to Json.Net. Whatever is the easiest is what I'm after. Commented Oct 17, 2018 at 15:59
  • 1
    @onTheInternet This page in the docs should be all you need Commented Oct 17, 2018 at 16:00
  • Can the downvoter explain? I believe I've followed the rules and it's certainly reasonable to say that other newbies like myself will find this information valuable. Commented Oct 17, 2018 at 16:09

3 Answers 3

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);
Sign up to request clarification or add additional context in comments.

3 Comments

I'm upvoting because even though I didn't use this solution, I tested it out and found it worked. So this is good information.
I think the attribute is [JsonProperty("someName")]
@maccettura you are right, it will work with JsonProperty. However this also works with DataMember attribute from System.Runtime.Serialization
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();

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.