In .NET 5 and above, we cannot directly use JsonPropertyName
to specify custom values for enumeration values like we can with normal properties. This feature is not available out of the box.
To solve this problem, we introduced a JsonConverter factory (JsonEnumMemberStringEnumConverter
) that leverages JsonStringEnumConverter
and adapted it to use a custom [EnumMember(Value="xxx")]
for each enum type annotated with JsonNamingPolicy
. For example:
<code class="language-csharp">[EnumMember(Value = "Trick-Or-Treat")] // 自定义值 public enum Example { Trick, Treat, TrickOrTreat }</code>
Custom converter registration and usage:
<code class="language-csharp">var options = new JsonSerializerOptions { Converters = { new JsonEnumMemberStringEnumConverter() }, // ... }; var json = JsonSerializer.Serialize(values, options);</code>
This converter has the following advantages:
JsonStringEnumConverter
. Alternatively, we can use the Macross.Json.Extensions
package, which provides a JsonStringEnumMemberConverter
that after installation allows us to annotate the enumeration as follows:
<code class="language-csharp">[JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumMemberConverter))] public enum Example { Trick, Treat, [EnumMember(Value="Trick-Or-Treat")] TrickOrTreat }</code>
If you need finer control, or need to support enums with custom values in versions of .NET earlier than 6.0, you can create a generic converter factory and converter from scratch. This approach is more complex and may require backporting for earlier versions.
[Flags]
attributes may require a modified JsonConverter
. See the instructions in the response for more details on handling this situation. JsonStringEnumConverter
would ignore its JsonNamingPolicy
during deserialization. This issue was fixed in pull request 73348. [EnumMember]
and [JsonPropertyName]
attributes, the value of [EnumMember]
in the custom converter will take precedence. The above is the detailed content of How to Customize Enum Values in System.Text.Json?. For more information, please follow other related articles on the PHP Chinese website!