2

I am working on an OAUTH2 login for a winforms applications.

I have to make a request to our with some credentials, and the server will respond with a token and json format.

What's the best approach to parse out the token value?

Here is the response format:

{
    "access_token":"asdfasdfasdfafbasegfnadfgasdfasdfasdf",
    "expires_in":3600,
    "token_type":"Bearer"
}
0

2 Answers 2

7

Create a class with those properties and use JSON.NET JsonConvert.SerializeObject method.

public class MyResponse
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }
    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }
    [JsonProperty("token_type")]
    public string TokenType { get; set; }
}

MyResponse response = new MyResponse();
// Fill in properties
string json = JsonConvert.SerializeObject(response);
Sign up to request clarification or add additional context in comments.

3 Comments

You should deserialize, not serialize. A response is deserialized...
Thought he want to build a response...in that case if you have the JSON response, then replace JsonConvert.SerializeObject to JsonConvert.DeserializeObject<MyResponse>(jsonString).
@Mark...can you confirm...do you want to extract the access_token from a JSON response string?
2

For less code you could also use JSON.NET with the dynamic type like the following;

public void JValueParsingTest()
{
    var jsonString = @"{""Name"":""Rick"",""Company"":""West Wind"",
                        ""Entered"":""2012-03-16T00:03:33.245-10:00""}";

    dynamic json = JValue.Parse(jsonString);

    // values require casting
    string name = json.Name;
    string company = json.Company;
    DateTime entered = json.Entered;

    Assert.AreEqual(name, "Rick");
    Assert.AreEqual(company, "West Wind");            
}

Source:http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing

3 Comments

I would never use dynamic if I don't have to. You don't want compiler errors on runtime.
I suppose it depends if he is adequately unit testing his work. There is no such thing as compiler errors at run-time, but i know you mean; you would like to benefit from compile time checking. Fair enough. I would recommend staying away from any interpreted languages!
I wanted to use the "dynamic" method, but part of my C# code is in a Xamarin environment on iOS. Apple doesn't allow dynamically generated code on iOS, so "dynamic" didn't work. Ended up creating the class and using JsonConvert to serialize/deserialize the oauth info as described by @MotoSV. Worked great. However, just to add a little more about how useful "dynamic" has been.... I have some server side code that I use to work with arbitrary JSON data coming in and a Mongo DB. We use "dynamic" all over the place there.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.