Vinicius Quinafelex Alves

🌐English version

Alterar formato JSON nos responses ASPNET Core

Internamente, o ASPNET Core utiliza a biblioteca System.Text.Json.JsonSerializer para serializar responses e desserializar requests. Quando o request está em um formato diferente do padrão do ASPNET, é possível alterar o formato registrando um JsonConverter.

CustomJsonConverter.cs

public class CustomJsonConverter : JsonConverter<int?>
{
    public override int? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        switch (reader.TokenType)
        {
            case JsonTokenType.String:
            {
                if(int.TryParse(reader.GetString(), out var value))
                    return value;

                break;
            }

            case JsonTokenType.Number:
            {
                return reader.GetInt32();
            }
        }

        return null;
    }

    public override void Write(Utf8JsonWriter writer, int? value, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize<int?>(writer, value, options);
    }
}

Program.cs

builder.Services.AddControllersWithViews().AddJsonOptions((option) => 
{
    option.JsonSerializerOptions.Converters.Add(new CustomJsonConverter());
});