I'm trying to make a POST
on an API so I can get a bearer token.
Example:
var client = new RestClient("https://api");
var request = new RestRequest();
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("client_id", "X");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_secret", "X");
var response = client.Post(request);
Console.WriteLine(response.Content);
The response is this JSON:
{
"access_token": "aisodjaisjd4123",
"token_type": "Bearer",
"expires_in": 3599
}
How can I store that aisodjaisjd4123
into a variable?
CodePudding user response:
You can serialise this json to a class object. And then access_token member will have token value.
You can use NewtonSoft.Json to deserialise the string to object. You can search it in Nuget Package manager.
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Root
{
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in { get; set; }
}
And please ignore the indentation, I have typed from phone.