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 应用于所有枚举
基础教程推荐
- 在 VB6 或经典 ASP 中使用 .NET 2022-01-01
- 从 C# 控制相机设备 2022-01-01
- 更新 Visual Studio 中的 DataSet 结构以匹配新的 SQL 数据库结构 2022-01-01
- SonarQube C# 分析失败“不是指针的有效行偏移" 2022-01-01
- 获取C#保存对话框的文件路径 2022-01-01
- 将数据集转换为列表 2022-01-01
- C# 9 新特性——record的相关总结 2023-04-03
- 如果条件可以为空 2022-01-01
- 重新排序 WPF TabControl 中的选项卡 2022-01-01
- Mono https webrequest 失败并显示“身份验证或解密失败" 2022-01-01
