Change JSON format on ASPNET Core responses
Internally, ASPNET Core uses System.Text.Json.JsonSerializer to serialize responses and deserialize requests. If an input uses a different format than the default ASPNET configuration, it is possible to change it by registering a 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());
});