0

There seems to be a problem with System.Text.Json.JsonSerializer.Deserialize in .Net Core 3.1

This code:

public class AuthAccessToken
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }

    [JsonProperty("expires_in")]
    public int ExpiresIn { get; set; }

    [JsonProperty("scope")]
    public string Scope { get; set; }

    [JsonProperty("token_type")]
    public string TokenType { get; set; }

    [JsonProperty("refresh_token")]
    public string RefreshToken { get; set; }
}

public async Task<AuthAccessToken> GetAccessTokenAsync(string code)
{
    using (var client = _clientFactory.CreateClient())
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
        client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _accessToken);
        client.BaseAddress = new Uri(API_URL);

        var keyValues = new List<KeyValuePair<string, string>>()
        {
            new KeyValuePair<string, string>("grant_type", "authorization_code"),
            new KeyValuePair<string, string>("code", code),
            new KeyValuePair<string, string>("client_id", CLIENT_ID),
            new KeyValuePair<string, string>("client_secret", CLIENT_SECRET),
            new KeyValuePair<string, string>("redirect_uri", CALLBACK_URL)
        };

        using (var content = new FormUrlEncodedContent(keyValues))
        {
            using (HttpResponseMessage response = await client.PostAsync("oauth/token", content))
            {
                if (response.IsSuccessStatusCode)
                {
                    string result = await response.Content.ReadAsStringAsync();
                    // The next line returns an object with all fields null
                    AuthAccessToken token = JsonSerializer.Deserialize<AuthAccessToken>(result);
                    // The next line works
                    token = JsonConvert.DeserializeObject<AuthAccessToken>(result);
                    return token;
                }
                else
                    return null;
            }
        };
    };
}

When I try to deserialize the JSON using JsonSerializer.Deserialize, the returned object has all its fields set to null. When I try do the exact same thing with JsonConvert.DeserializeObject (NewtonSoft) then it works.

The JSON looks like this:

{
  "token_type": "Bearer",
  "expires_in": 7200,
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6IjQ5MGE0NDFjN2E3NTI2NmRmZGE5YjA4MDNiZmFmNTM3OTk1MjM5Mzgw...",
  "refresh_token": "def50200ae465b5fcc53898bf8b3a42fdcb9de974a012fa69cd87ac4a5d8573934db89b27e212e1b3faf9fd6b22df03a1b44..."
}

Any ideas?

Fabricio Rodriguez
  • 3,769
  • 11
  • 48
  • 101
  • 1
    You also need to override the property names for `System.Text.Json` by adding `[System.Text.Json.Serialization.JsonPropertyName("access_token")]` attributes to your model. See [Converting newtonsoft code to System.Text.Json in .net core 3. what's equivalent of JObject.Parse and JsonProperty](https://stackoverflow.com/a/58273914/3744182) - in fact I think this is a duplicate, agree? – dbc Jul 15 '20 at 12:40
  • 1
    Yes, that works. See https://dotnetfiddle.net/Zuc4bS – dbc Jul 15 '20 at 13:33
  • 1
    That was indeed the problem. Thank you dbc! – Fabricio Rodriguez Jul 16 '20 at 12:02

0 Answers0