1

I need to serialize and object into JSON to pass the payload to a Python script. The properties with null values in C# should have None value in the JSON passed to Python in order to work. I have created an JsonConverter to check if the value is null and write None instead. However is never called. As one of the properties that can be null is of type string (others can be float?, int?, etc) I have also created a JsonConverter:

public class NullJsonConverter : JsonConverter<string>
{
    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var jsonString = reader.GetString();

        if (!string.IsNullOrEmpty(jsonString))
        {
            return JsonSerializer.Deserialize<string>(jsonString, options);
        }

        return null;
    }

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        if (value == null)
        {
            //Logic to convert from null to None
        }

        JsonSerializer.Serialize(writer, value);
    }
}

However when I serialize an object that contains a property of type string the converter is only called when the property has a value.

This are the options that I'm using for the serialization:

return new JsonSerializerOptions()
{
    DefaultIgnoreCondition = JsonIgnoreCondition.Never,
    WriteIndented = true,
    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
    Converters =
    {
        new JsonStringEnumConverter(),
        new NullJsonConverter()
    }
};

What am I missing? How can I serialize in C# and object so the null properties are reflected as None in the JSON and when de-serializing back are converted back to null?

eng
  • 443
  • 1
  • 4
  • 10
Jaime
  • 131
  • 9
  • 1
    Override `HandleNull => true;` as shown in [this answer](https://stackoverflow.com/a/67286291/3744182) to [System.Text.Json Serialize null strings into empty strings globally](https://stackoverflow.com/q/59792850/3744182). In fact I think this is a duplicate, agree? – dbc Aug 01 '23 at 08:34

1 Answers1

1

Try overriding the HandleNull property and set it to true. Like described in this issue: https://github.com/dotnet/runtime/issues/44006#issuecomment-719002484

public class NullJsonConverter : JsonConverter<string>
{
    public override bool HandleNull => true;

    public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
    {
        var jsonString = reader.GetString();

        if (!string.IsNullOrEmpty(jsonString))
        {
            return JsonSerializer.Deserialize<string>(jsonString, options);
        }

        return null;
    }

    public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
    {
        if (value == null)
        {
            //Logic to convert from null to None
        }

        JsonSerializer.Serialize(writer, value);
    }
}
Magnus
  • 45,362
  • 8
  • 80
  • 118