我想用 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 应用于所有枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
读取 XML 时忽略空格Ignore whitespace while reading XML(读取 XML 时忽略空格)
带有检查空元素的 XML 到 LINQXML to LINQ with Checking Null Elements(带有检查空元素的 XML 到 LINQ)
在 C# 中读取带有未闭合标签的 XMLReading XML with unclosed tags in C#(在 C# 中读取带有未闭合标签的 XML)
在 C# 中使用 Html 敏捷性解析表格、单元格Parsing tables, cells with Html agility in C#(在 C# 中使用 Html 敏捷性解析表格、单元格)
使用 LINQ 从 xml 中删除元素delete element from xml using LINQ(使用 LINQ 从 xml 中删除元素)
解析格式错误的 XMLParse malformed XML(解析格式错误的 XML)