I have this code that gets the token from RestAPI
// Prepare JSON content
var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(tokenEndpoint, content);
if (response.IsSuccessStatusCode)
{
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Token received: " + responseBody);
return responseBody;
}
else
{
Console.WriteLine($"Failed to obtain access token (GetAccessToken). Status code: {response.StatusCode}");
return null;
}
The return responseBody;
It includes the token but other items as well (token,refresh..). Looks like this:
{"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6ImFkbWluIiwibmJmIjoxNzE5MDI0ODM2LCJleHAiOjE3MTkwMjU0MzYsImlhdCI6MTcxOTAyNDgzNn0.USYqigcN_vGa5tfEaOW0u9RvPpWQIOLdyRb05Fc0RII","refreshToken":""}
I’ve tried
//deserialize token
var outObject = JsonConvert.DeserializeObject<dynamic>(responseBody);
return outObject.access.token;
but did not work. Read some post in this forum but the token format was different.
How do I convert that into just the token string before I return it?
2
Answers
Approach 1
Create a model class (
TokenResponse
) and deserialize the JSON asTokenResponse
.Approach 2
Working with
JObject
and extract thetoken
field.You can create a generic method for json serialization and deserialization as below
With a class as below.
You can now use it to extract your body as below.
Hope it helps.