Using:
- .net 8
- System.Text.Json serializer.
Let's say I have a two classes defined like this:
public class SampleClass
{
public SampleClassDetail? FirstProperty { get; set; }
public SampleClassDetail? SecondProperty { get; set; }
}
public class SampleClassDetail
{
public int MyProperty { get; set; }
}
And an instance of SampleClass :
SampleClass sample = new()
{
FirstProperty = new SampleClassDetail { MyProperty = 1 }
};
Then I want to serialize it with System.Text.Json:
string serialized = JsonSerializer.Serialize(sample);
This produces:
{
"FirstProperty": {
"MyProperty": 1
},
"SecondProperty": null
}
But I would the null to be treated like: "SecondProperty": {}
I've tried creating a CustomJson Converter and adding it to the options:
public class SampleClassDetailConverter : JsonConverter<SampleClassDetail?>
{
public override SampleClassDetail? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
public override void Write(Utf8JsonWriter writer, SampleClassDetail? value, JsonSerializerOptions options)
{
if (value == null)
{
writer.WriteStartObject();
writer.WriteEndObject();
}
else
{
var newOptions = new JsonSerializerOptions(options);
newOptions.Converters.Remove(this);
JsonSerializer.Serialize(writer, value, newOptions);
}
}
}
var options = new JsonSerializerOptions();
options.Converters.Add(new SampleClassDetailConverter());
string serialized = JsonSerializer.Serialize(sample, options);
But still getting the same.