Home > Blockchain >  Object is null after JsonConvert.DeserializeObject
Object is null after JsonConvert.DeserializeObject

Time:12-29

I have looked at some forum posts and found no solution to my problem, so now I ask you for help. First i show you what the result of my HttpGet is and then i show you the not working deserialization.

Working example: I use the same code for an HttpGet to get a json result.

    [HttpGet]
    [Route("~/get_new_authtoken")]
    public async Task<IActionResult> GetNewAuthTokenAsync()
    {
        try
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("https://testApi/WebService/");
            string APIConnection = _configuration.GetValue<string>("APIConnection");
            HttpResponseMessage response = client.PostAsync("authtoken", new StringContent(string.Format(APIConnection))).Result;
            if (response.IsSuccessStatusCode)
            {
                var token = JsonConvert.DeserializeObject<AuthToken>(await response.Content.ReadAsStringAsync());
                return Ok(response.Content.ReadAsStringAsync().Result);
            }
            else
            {
                return BadRequest(response.Content.ReadAsStringAsync().Result);
            }
        }
        catch (Exception ex)
        {
            SentrySdk.CaptureException(ex);
            return Ok(ex.Message); 
        }
    }

with following result when i call it via Postman

Result in Postman

Not working deserialization: I store the token in a database and want to update it when it expires.

Object i want to desiralize in:

public class AuthToken
{
    [JsonPropertyName("access_token")] public string AccessToken { get; set; }
    [JsonPropertyName("refresh_token")] public string RefreshToken { get; set; }
    [JsonPropertyName("token_type")] public string TokenType { get; set; }
    [JsonPropertyName("expires_in")] public int ExpiresIn { get; set; }
}

when i add the following code to the httpget above to test the deserializationthe object Authtoken is always null.

 AuthToken newAccessToken = new AuthToken();
 newAccessToken = JsonConvert.DeserializeObject<AuthToken>(await response.Content.ReadAsStringAsync());

Like this->

            if (response.IsSuccessStatusCode)
            {
                //To test
                AuthToken newAccessToken = new AuthToken();
                newAccessToken = JsonConvert.DeserializeObject<AuthToken>(await response.Content.ReadAsStringAsync());
                //To test
                var token = JsonConvert.DeserializeObject<AuthToken>(await response.Content.ReadAsStringAsync());
                return Ok(response.Content.ReadAsStringAsync().Result);
            }
            else
            {
                return BadRequest(response.Content.ReadAsStringAsync().Result);
            }

Updated the testint to following code:

 AuthToken newAccessToken = new AuthToken();
 var responseString = await response.Content.ReadAsStringAsync();
 newAccessToken = JsonConvert.DeserializeObject<AuthToken>(responseString);

result of the responseString: result of ReadAsStringAsync

CodePudding user response:

JsonPropertyNameAttribute is from System.Text.Json while JsonConvert.DeserializeObject is part of Newtonsoft.Json either switch to former completely by using System.Text.Json.JsonSerializer.Deserialize:

AuthToken newAccessToken = JsonSerializer.Deserialize<AuthToken>(...); 
// or just use ReadFromJsonAsync instead of ReadAsStringAsync

Or use attributes for latter:

public class AuthToken
{
    [JsonProperty("access_token")]
    public string AccessToken { get; set; }
    // ...
}
  • Related