1

I have API controller -.net core 3.1-

when I call method I get response object with its properties.

some of this might be null string.

How can I configure my API to return empty string instead of null ?

Can I do this in Startup.cs ?

Edit

I used this option: services.AddMvc().AddJsonOptions(options => { options.JsonSerializerOptions.IgnoreNullValues = true; });

but it'll hide null properties, which I don't want.

Yinqiu
  • 6,609
  • 1
  • 6
  • 14
Mu nt
  • 93
  • 1
  • 1
  • 9

1 Answers1

2

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 "".

malthe.w
  • 77
  • 10