我想要以下全局 Json.NET 配置:
- 如果枚举类型是
Foo
,使用枚举的默认序列化逻辑(输出整数值,例如3
)。 - 否则,使用
StringEnumConverter
(输出字符串值,例如"Red"
)
我想使用全局配置,因为 Web API 的 ApiController 会自动将响应转换为 JSON。
// Global Json.NET configuration in Global.asax.cs
HttpConfiguration config = GlobalConfiguration.Configuration;
// Serialize enum values as description instead of integers in JSON.
// I wish to conditionally apply this converter.
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new
StringEnumConverter());
当前结果:
- 始终使用
StringEnumConverter
。
这里推荐的解决方案是什么?
最佳答案
您可以通过创建一个派生自 Json.Net 的 StringEnumConverter
的自定义 JsonConverter
来做到这一点。在 WriteJson
方法中,检查该值是否为 Foo
枚举,如果是,则将其写入整数。否则,使用基类WriteJson
方法写入值。 (您不需要覆盖 ReadJson
,因为 StringEnumConverter
已经处理读取字符串和数值。)
class StringEnumExceptFooConverter : StringEnumConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is Foo || value is Foo?)
{
writer.WriteValue(value);
}
else
{
base.WriteJson(writer, value, serializer);
}
}
}
然后,在您的配置中,将 StringEnumConverter
替换为您的自定义转换器。
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new StringEnumExceptFooConverter());
演示 fiddle (控制台应用程序):https://dotnetfiddle.net/3iUIKT
关于c# - 根据类型配置全局 Json.NET 转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44109199/