4

I'm using .net core 5, NOT USING NEWTONSOFT. I'm writing a custom serializer because the case output of my json is weird; but I don't mind using the standard deserializer.

I have the following code, following the microsoft guide on writing custom jsonConverters:

public class ThingConverter : JsonConverter<Thing>{
  public override void Write(Utf8JsonWriter writer, Thing t, JsonSerializerOptions options){
    // do stuff, this is fine
  }
  public override Thing Read(ref Utf8Reader reader, Type typeToConvert, JsonSerializerOptions options){
    // i want the DEFAULT behaviour here.
  }
}

Would anyone know how to have the default behaviour for the reader?

Things I've tried:

  • return JsonSerializer.Deserialize<Thing>(ref reader, options) -> gives an infinite loop
  • add public override bool CanConvert(Type objectType){return false;} -> Throws runtime error, cannot convert

fwiw, I'm using the declaration

[JsonConverter(typeof(ThingConverter))]
public class Thing{
}

to register the converter globally.

acenturyandabit
  • 1,188
  • 10
  • 24
  • 1
    It seems to be impossible to make `System.Text.Json` generate a default serialization for a type to which you have applied `[JsonConverter(typeof(ThingConverter))]` *directly to the type itself*. There are ways to do it if the converter is applied in options, or on a specific property. See: [How to use default serialization in a custom System.Text.Json JsonConverter?](https://stackoverflow.com/q/65430420/3744182). – dbc Apr 16 '21 at 14:39

1 Answers1

0

If you'd like to change the property names only, use [JsonPropertyName("Name")]. https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-customize-properties

acenturyandabit
  • 1,188
  • 10
  • 24