Okay so after having the same challenge and researching a bunch, I found out that you can absolutely convert NULLs to empty strings and still have these properties show in your frontend.
I used this other answer (https://stackoverflow.com/a/67286291/11463515) as a reference and did the following.
Step 1:
Create a new class file in the same directory as your Startup.cs
file and name it NullToEmptyStringConverter.cs
with the following code:
using System;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace API
{
public class NullToEmptyStringConverter : JsonConverter<string>
{
// Override default null handling
public override bool HandleNull => true;
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) =>
reader.TokenType == JsonTokenType.Null ? "" : reader.GetString();
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) =>
writer.WriteStringValue(value ?? "");
}
}
Make sure that both your Startup.cs
and NullToEmptyStringConverter.cs
are using the same namespace!
Step 2:
After creating the NullToEmptyStringConverter.cs
file, you can now simply add the following to your services.AddControllers()
method so it looks like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers()
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new NullToEmptyStringConverter());
});
}
And that should be it! With this, all string values that have the value NULL
or null
in your response will be replaced with ""
.