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?