skip to Main Content

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


  1. Approach 1

    Create a model class (TokenResponse) and deserialize the JSON as TokenResponse.

    public class TokenResponse
    {
        public string Token { get; set; }
        public string RefreshToken { get; set; }
    }
    
    var outObject = JsonConvert.DeserializeObject<TokenResponse>(responseBody);
    return outObject.Token;
    

    Approach 2

    Working with JObject and extract the token field.

    using Newtonsoft.Json.Linq;
    
    var outJObject = JObject.Parse(responseBody);
    return outJObject["token"].ToString();
    
    Login or Signup to reply.
  2. You can create a generic method for json serialization and deserialization as below

    // NOTE HERE: I am using System.Text.Json
    using System.Text.Json;
    
    namespace DemoApp.Extensions;
    
    public static class JsonSerializerExtensionMethods
    {
        private static readonly JsonSerializerOptions options = new()
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase
        };
    
        public static string ToJson<T>(this T @object, JsonSerializerOptions? jsonSerializerOptions = null)
            => JsonSerializer.Serialize(@object, jsonSerializerOptions ?? options);
    
        public static byte[] ToJsonToUtf8Bytes<T>(this T @object, JsonSerializerOptions? jsonSerializerOptions = null)
            => JsonSerializer.SerializeToUtf8Bytes(@object, jsonSerializerOptions ?? options);
    
        // This is the method you need to extract your json data
        public static T? FromJson<T>(this string text, JsonSerializerOptions? jsonSerializerOptions = null)
            => string.IsNullOrWhiteSpace(text) ? default : JsonSerializer.Deserialize<T>(text, jsonSerializerOptions ?? options);
    
        public static T? FromJson<T>(this byte[] mByte, JsonSerializerOptions? jsonSerializerOptions = null)
            => mByte is null ? default : JsonSerializer.Deserialize<T>(mByte, jsonSerializerOptions ?? options);
    }
    

    With a class as below.

    public class TokenResponse
    {
        public string Token { get; set; }
        public string RefreshToken { get; set; }
    }
    

    You can now use it to extract your body as below.

    string responseBody = await response.Content.ReadAsStringAsync();
    Console.WriteLine("Token received: " + responseBody);
    
    //NOTICE HERE HOW I HAVE USED THE "FromJson"
    var tokenResponseResult = responseBody.FromJson<TokenResponse>();
    Console.WriteLine("Token token received: " + tokenResponseResult.Token);
    

    Hope it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search