如何判断Json.Net在全球范围内的StringEnumConverter适用于所有枚举 [英] How to tell Json.Net globally to apply the StringEnumConverter to all enums
问题描述
我要反序列化枚举,以它们的字符串重新presentation,反之亦然json.net。我可以找出告诉框架应用的唯一途径了 StringEnumConverter
的注释有问题的性质是这样的:
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; }
不过,在我使用的情况下,这将是更方便的配置json.net全球范围内,使所有枚举得到的(de)使用序列化的 StringEnumConverter
,而不需要额外的注解。
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.
有没有办法做到这一点,例如自定义的帮助 JsonSerializerSettings
?
Is there any way to do so, e.g. with the help of custom JsonSerializerSettings
?
推荐答案
添加 StringEnumConverter
到 JsonSerializerSettings
转换器集合。
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 });
这将连载 someValue中
来someValue中。
This will serialize SomeValue
to "someValue".
这篇关于如何判断Json.Net在全球范围内的StringEnumConverter适用于所有枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!