Skip to content

JsonConverterAttribute cannot be applied to an Enum #30361

@Joelius300

Description

@Joelius300

Since I'm trying to migrate from Newtonsoft.Json to the new System.Text.Json APIs, I have to be able to use a Enum-string converter.

In json.net you can do this really easily with this attribute on the enum.

[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))]

Since there is both a JsonConverterAttribute and a JsonStringEnumConverter class, I thought you would do it like this:

[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter))]

However after getting a compiler error I quickly realized that the JsonConverterAttribute can't even be used on an Enum because it only has the following three AttributeTargets-flags.

  • AttributeTargets.Class
  • AttributeTargets.Struct
  • AttributeTargets.Property

Are you not supposed to use this attribute and converter like this?
Are there any samples because there I've not found any in the docs?

Metadata

Metadata

Assignees

Labels

area-System.Text.JsonenhancementProduct code improvement that does NOT require public API changes/additions

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions