Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Text.Json Serialize null strings into empty strings globally

While migrating code from newtonsoft json to system.text.json

I need all nullable strings to render as empty string.

I wrote following converter but all null string values are still rendered as null.

And for null string values, Write method is not called. Break point is never hit.

public class EmptyStringConverter : JsonConverter<string>
{
    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        => Convert.ToString(reader.GetString(), CultureInfo.CurrentCulture);

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        if (writer == null)
            throw new ArgumentNullException(nameof(writer));
        writer.WriteStringValue(value ?? "");
    }
}

Startup code

services.AddControllers()
    .AddJsonOptions(option =>
    {
        option.JsonSerializerOptions.Converters.Add(new EmptyStringConverter());
    });

Console Example

class Program
{
    static void Main(string[] args)
    {
        var jsonSerializerOptions = new JsonSerializerOptions();
        jsonSerializerOptions.Converters.Add(new EmptyStringConverter());
        var json = JsonSerializer.Serialize(new Model() { FirstName = null }, jsonSerializerOptions);
    }
}

public class EmptyStringConverter : JsonConverter<string>
{
    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        => Convert.ToString(reader.GetString(), CultureInfo.CurrentCulture);

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        if (writer == null)
            throw new ArgumentNullException(nameof(writer));
        writer.WriteStringValue(value ?? "");
    }
}

public class Model
{
    public string FirstName { get; set; }
}
like image 662
Khalil Avatar asked Sep 02 '26 00:09

Khalil


1 Answers

In .NET 5.0 this can be done by overriding JsonConverter<T>.HandleNull and returning true:

public class EmptyStringConverter : JsonConverter<string>
{
    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 ?? "");
}

For more, see Handle null values.

Demo fiddle here.

In .NET Core 3.x this is not implemented. From Handle null values in .NET Core 3.x:

Handle null values

By default, the serializer handles null values as follows:

  • For reference types and Nullable<T> types:

    • It does not pass null to custom converters on serialization.
    • It does not pass JsonTokenType.Null to custom converters on deserialization.
    • It returns a null instance on deserialization.
    • It writes null directly with the writer on serialization.
  • For non-nullable value types:

    • It passes JsonTokenType.Null to custom converters on deserialization. (If no custom converter is available, a JsonException exception is thrown by the internal converter for the type.)

This null-handling behavior is primarily to optimize performance by skipping an extra call to the converter. In addition, it avoids forcing converters for nullable types to check for null at the start of every Read and Write method override.

like image 51
dbc Avatar answered Sep 04 '26 13:09

dbc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!