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 应用于所有枚举


基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01