0

I had the following converter to serialize the date with a custom format and it was working for .NET Core 3.1:

public class CustomDateConverter : IsoDateTimeConverter {
    public CustomDateConverter() {
        base.DateTimeFormat = "dd.MM.yyyy";
    }
}

public class Test {
    [JsonConverter(typeof(CustomDateConverter))]
    public DateTime? CustomFormattedDate { get; set; }
}

However, after I migrated to .NET 6.0 the converter no longer gets called. The only way I found was to add the converter to the global list of converters at configuration time, but then it will be used for every DateTime field in my project, which is not what I want. Btw, my configuration looks like this:

builder.Services.AddControllersWithViews()
    .AddNewtonsoftJson(options => {
        options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
        options.SerializerSettings.ContractResolver = new DefaultContractResolver();
        // options.SerializerSettings.Converters.Add(new CustomDateConverter());
    });
rabusmar
  • 4,084
  • 1
  • 25
  • 29
  • 1
    Are you sure you are applying [`Newtonsoft.Json.JsonConverterAttribute`](https://www.newtonsoft.com/json/help/html/t_newtonsoft_json_jsonconverterattribute.htm) and not [`System.Text.Json.Serialization.JsonConverterAttribute`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.jsonconverterattribute)? Try using the fully qualified name `[Newtonsoft.Json.JsonConverter(typeof(CustomDateConverter))]` and see if the problem resolves. Also, make sure that the version of Json.NET that your DLL was built with matches the version used by the framework in runtime. – dbc Mar 04 '23 at 21:17
  • See also [JsonConverter not working as property attribute](https://stackoverflow.com/q/49248429/3744182). (The accepted self-answer is very cryptic unfortunately.) – dbc Mar 04 '23 at 21:21
  • Yes, I'm using the the correct class (remember that it was working fine for .NET Core 3.1). Using the FQN gives the same result. – rabusmar Mar 04 '23 at 21:53

0 Answers0