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 应用于所有枚举
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
