Search code examples
c#json

system text json use standard deserialization


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.


Solution

  • 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