I have written a system.text.json custom converter for the Read()
side of the custom converter. However, for the Write()
side, I would simply like to use the default Write functionality to serialise an object instead of having to hand roll the serialisation of an object. I started with...
public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
I had hoped that I could simply use the standard JsonSerializer.Serialize(Customer)
within the Write()
method. Something like...
public override void Write(Utf8JsonWriter writer, Customer value, JsonSerializerOptions options)
{
return JsonSerializer.Serialize(value);
}
However, that appears to be returning null
. I imagine that all I am doing is nesting the same behaviour.
As a sign of desperation, I have also tried deleting the Write()
method hoping that the standard functionality would fill that gap, but I get the following Build error message...
CS0534 'CustomerJsonConverter' does not implement inherited abstract member
'JsonConverter<Customer>.Write(Utf8JsonWriter, Customer, JsonSerializerOptions)'
Newtonsoft.Json has properties called CanRead
and CanWrite
that can be set to False. These force the converter to use the default converter functionality when deserializing and serializing respectively.
I'm hoping there's something similar in System.Text.Json?
Update 1
Using @Guilherme's suggestion... it part works. However, that approach gives an incomplete Json object.
For background, when I Deserialize my original source Json, I am having to deal with a situation where the originating Json (over which I have no control), has a field that can be an empty ""
, or an object { "key": "value" }
or an array [{ "key": "value" },{ "key": "value" }]
. In the Read()
(deserializer) I handle this and output a consistent array.
But now, when I serialise my resulting object, the Addresses array is always empty (blank). Here's the output when I leave the Write()
method empty. Note that "Addresses" has no value or comma separator.
{
"Customer": {
"firstName": "John",
:
other values
:
"Addresses": "Phone": "01234567890"
}
}
Do I have to roll my own JsonDocument and use that in the Write method?