Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse HTTP JSON Response - C# [duplicate]

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"
}
like image 253
Mark Avatar asked Apr 24 '26 23:04

Mark


2 Answers

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);
like image 138
MotoSV Avatar answered Apr 26 '26 11:04

MotoSV


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

like image 39
adampolar Avatar answered Apr 26 '26 11:04

adampolar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!