How to write custom json converter with custom read and default write?

Viewed 172

I'm building an ASP.NET Core 3.1 Web API.
Using the System.Text.Json (the default lib comes with .net core 3.1) I need to write a CustomJsonConverter for a custom generic type (ley's call it MyType<T>), but need only to customize the deserialization functionality (only the Read method), and leave the Write to work as if there was no custom converter to this type, it's an object so I need it to be serialized as an object.

I tried this:

public class MyTypeConverter<T> : JsonConverter<T>
  where T : MyType<T>
{
    public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {  
          // do the custom deserialization
    }
    
    public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options) {
         // I tried the following but it resulted a "string" json object, not object in Json format
         // like this: "{\"Key\":1,\"Value\":\"Male\"},{\"Key\":2,\"Value\":\"Female\"}"
         //JsonSerializer.Serialize(writer, value, options);
    }
}

Is there a way to keep the write as in the default converter?

0 Answers
Related