0

I have defined a custom Json Convertor for my DTO as below

public class CustomJsonConverter<T> : JsonConverter<T> where T : class
    {
        public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
        {
            some code...
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            some code...
        }
    }

Then i am using it on my DTO as below

[JsonConverter(typeof(CustomJsonConverter<StudentDTO>))]
    public class StudentDTO
    {
            some code...
    }

Its all working super fine. Now All I want is At some place I want .net to use My JsonConverter and in other places i want .net to use default JsonConverter. How Do I Do it

Is there a way where I remove the converter annotation from the DTO and instead Use "JsonSerialzer.Serialize()" and somehow I can tell it which converter to use.

dbc
  • 104,963
  • 20
  • 228
  • 340
  • 1
    You can use `JsonSerializerOptions` and add a new instance of your custom converter to the proerty `Converters`, it's documented on MSDN: [system-text-json - converters-how-to](https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/converters-how-to?pivots=dotnet-7-0), and yes, remove the attribute on your class if you are going to serialize it in different ways. You can pass the `JsonSerializerOptions` as a parameter in the overload of `Deserialize` and `Serialize` – Ryan Wilson Dec 07 '22 at 19:55
  • You can't. Once you apply the converter **to the class itself**, it will always be used in preference to default serialization. See [How to use default serialization in a custom System.Text.Json JsonConverter?](https://stackoverflow.com/a/65430421/3744182). Only thing I can think to do would be to subclass `StudentDTO` when you don't want to use the converter (or vice versa, when you do). Or remove `[JsonConverter(typeof(CustomJsonConverter))]` and add the converter to `JsonSerializerOptions.Converters` as recommended by @RyanWilson. – dbc Dec 13 '22 at 18:33

0 Answers0