Home > OS >  How to inject dependency in Newtonsoft JsonConverter in .net core 5.0
How to inject dependency in Newtonsoft JsonConverter in .net core 5.0

Time:12-23

I am trying to call a web API from my web application. I am using .Net 5.0 and while writing the code I am getting the error "The name 'JsonConvert' does not exist in the current "definition JsonConvert.DeserializeObject method. *So my question is what's the @inject... I need to use in order to use in razor page

@code { private Employee Employee{ get; set; } = new Employee();

private async void HandleValidSubmit()
{
    try
    {
        var response = await Http.PostAsJsonAsync("/api/Employee", Employee);
        response.EnsureSuccessStatusCode();

        var content = await response.Content.ReadAsStringAsync();
        var employee= JsonConvert.DeserializeObject<Employee>(content);
        Navigation.NavigateTo($"employee/edit/{employee.Id}");
    }
    catch (AccessTokenNotAvailableException exception)
    {
        exception.Redirect();
    }
    catch (Exception e)
    {
    }
}

}

CodePudding user response:

Try to add the following code into your razor page:

@using Newtonsoft.Json;

CodePudding user response:

"The name 'JsonConvert' does not exist ..."

Newtonsoft.Json is still available for backward compatibility.

The new API is System.Text.Json. You should use that unless you have a specific reason to use Newtonsoft.

You are already using the helper method PostAsJsonAsync that relies on System.text and does it all. All you need is two lines:

//var response = await Http.PostAsJsonAsync("/api/Employee", Employee);
var employee = await Http.PostAsJsonAsync<Employee>("/api/Employee", Employee);
Navigation.NavigateTo($"employee/edit/{employee.Id}");

If you do want to deserialize in detailed steps then it looks like

var content = await response.Content.ReadAsStringAsync();
var employee = System.Text.Json.JsonSerializer.Deserialize<Employee>(content);
  • Related