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"
}
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With