2

In .net core prior to version 3 there when Newtonsof.Json was used there was a possibility to inherit from StringEnumConverter to add additional validation or a custom error message for the process of binding a string to enum.

I cannot find it's counterpart in .Net Core 3. There is a JsonStringEnumConverter but it is sealed. It seems the only option is to write the whole converter myself and I'd like to avoid that.

P.S. I know it is possible to fall back to Newtonsoft.Json and use it as before, but I want to use the new Microsoft implementation.

dbc
  • 104,963
  • 20
  • 228
  • 340
Ilya Chernomordik
  • 27,817
  • 27
  • 121
  • 207
  • 2
    You can still use Json.net in .NET Core 3. It's just that .NET Core 3 introduced its own JSON library, `System.Text.Json`. This is not Json.net, and doesn't provide all of the same capabilities. – canton7 Feb 19 '20 at 14:26
  • Yes, I know, forgot to mention that I'd rather use the new json library :) – Ilya Chernomordik Feb 19 '20 at 14:39
  • Cool, it sounded like you were confused that `StringEnumConverter` had gone in .NET Core 3 specifically (i.e. in Json.net on .NET Core 3), and not in `System.Text.Json` – canton7 Feb 19 '20 at 14:40
  • there is often a lot of confusion around that if one does not read changelog from microsoft :) Fortunately they are doing a way better job now with these than before – Ilya Chernomordik Feb 19 '20 at 15:39
  • 1
    You could follow the decorator pattern and create your own `JsonConverterFactory` for enums that delegates to `JsonStringEnumConverter` for the default case but manufactures a specific converter for some override case. See e.g. [Exclude an enum property of a Model from using the JsonStringEnumConverter which is globally set at the Startup?](https://stackoverflow.com/q/59828937/3744182). – dbc Apr 19 '21 at 14:47
  • Or if `JsonStringEnumConverter` is too limiting (no support for custom names) you could use a third party converter like the one from [`Macross.Json.Extensions`](https://www.nuget.org/packages/Macross.Json.Extensions/). See e.g. [System.Text.Json: How do I specify a custom name for an enum value?](https://stackoverflow.com/q/59059989/3744182). – dbc Apr 19 '21 at 14:49

0 Answers0