Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
303 views
in Technique[技术] by (71.8m points)

c# - How to tell Json.Net globally to apply the StringEnumConverter to all enums

I want to deserialize enumerations to their string representation and vice versa with json.net. The only way I could figure out to tell the framework to apply its StringEnumConverter is to annotate the properties in question like this:

[JsonConverter(typeof(StringEnumConverter))]
public virtual MyEnums MyEnum { get; set; }

However, in my use case, it would be much more convenient to configure json.net globally such that all enumerations get (de)serialized using the StringEnumConverter, without the need of extra annotations.

Is there any way to do so, e.g. with the help of custom JsonSerializerSettings?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Add a StringEnumConverter to the JsonSerializerSettings Converters collection.

Documentation: Serialize with JsonConverters


If you want the serializer to use camelCasing, you can set this as well:

SerializerSettings.Converters.Add(
    new StringEnumConverter { CamelCaseText = true });

This will serialize SomeValue to someValue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...