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; }
}