How to tell Json.Net globally to apply the StringEnumConverter to all enums(如何全局告诉 Json.Net 将 StringEnumConverter 应用于所有枚举)
问题描述
我想用 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 会方便得多,这样所有枚举都可以使用 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
转换器集合.
Add a StringEnumConverter
to the JsonSerializerSettings
Converters collection.
文档:使用 JsonConverters 进行序列化
Documentation: Serialize with JsonConverters
如果你想让序列化器使用camelCasing,你也可以设置这个:
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 应用于所有枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何全局告诉 Json.Net 将 StringEnumConverter 应用于所有枚举


- 带问号的 nvarchar 列结果 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01