Click here to Skip to main content
15,885,757 members
Articles / Programming Languages / C#
Tip/Trick

JsonConverter Attribute in ASP.NET Core 3.0 Web API

Rate me:
Please Sign up or sign in to vote.
5.00/5 (9 votes)
22 Oct 2019CPOL2 min read 4.2M   2   3
ASP.NET Core 3.0 uses a built-in JSON converter from System.Text.Json so that JsonConverter attribute from Newtonsoft.Json does not work by default.

Introduction

In .NET Core 3.0, a built-in JSON converter is available in namespace System.Text.Json, and ASP.NET Core 3.0 uses this new JSON converter by default. Therefore, when you migrate your Web API from ASP.NET Core 2.x to 3.0, you need to replace JsonConverter attribute with System.Text.Json.Serialization.JsonConverter if you use it.

Migration to System.Text.Json

In ASP.NET Core 2.2 Web API, I had used Newtonsoft.Json.Converters.StringEnumConverter to convert enum values to the enumerator name at API response as shown below. In this case, the serialized JSON in the response looked like { "status": "Success", "message": "..." }.

C++
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

[JsonConverter(typeof(StringEnumConverter))]
public enum ApiResponseStatus
{
    Success,
    Failure
}

public abstract class ApiResponse

{
    public ApiResponseStatus Status { get; set; }
    public string Message { get; set; }
}

[Route("api/[Controller]")]
[ApiController]
public class MessagingController : ControllerBase
{
    [HttpPost("[action]")]
    public async Task<ApiResponse> Messages([FromBody] Message message)
    {
        return new ApiResponse
        {
            Status = ApiResponseStatus.Success,
            Message = "The POST request successfully completed."
        }
    }
}

When this code migrates to ASP.NET Core 3.0, it does not work. The serialized JSON turns to be { "status": 0, "message": "..." }. Let's replace the attribute with the attribute from System.Text.Json.

C++
using System.Text.Json.Serialization;

[JsonConverter(typeof(JsonStringEnumConverter))]
public enum ApiResponseStatus
{
    Success,
    Failure
}

The attribute name is the same as Newtonsoft.Json so that you just need to replace the namespace to System.Text.Json.Serialization. For some reason, the converter equivalent to StringEnumConverter is named JsonStringEnumConverter in System.Text.Json namespace. With this modification, the API will work in ASP.NET Core 3.0 as it does in 2.2.

Another Option: Keep using Newtonsoft.Json

In my case, there was an equivalent converter available, and the code migration was easy. However, you may want to keep using Nowtonsoft.Json, for example, if no equivalent converters are available or you have your own custom converter. In such a case, another option is to keep using Newtonsoft.Json.

Configuration to do this is quite simple. Newtonsoft.Json is now available from Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and it also has an extension method to configure it in a single method call. Add the NuGet package to your project, and call the extension method, AddNewtonsoftJson, after an MVC service registration method, which is AddControllers, AddControllersWithViews or AddRazorPages.

C++
public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews()
            .AddNewtonsoftJson();
    }
}

Having your Startup class like this, JsonConvert attribute from Newtonsoft.Json can still work at API response in ASP.NET Core 3.0 Web API.

History

  • 2019-10-23: Published the first edit

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
New Zealand New Zealand
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
eltoso31-Mar-20 22:12
eltoso31-Mar-20 22:12 
Questionreceive enum as string in netcore 3 controller Pin
Member 1340001229-Dec-19 11:04
Member 1340001229-Dec-19 11:04 
GeneralMy vote of 5 Pin
Satukan23-Oct-19 14:25
Satukan23-Oct-19 14:25 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.