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?