ora*_*rad 6 c# asp.net json.net asp.net-web-api
我在我的Web API项目中使用以下内容Startup.cs
将JSON序列化枚举为字符串:
// Configure JSON Serialization
var jsonSerializationSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
jsonSerializationSettings.Formatting = Newtonsoft.Json.Formatting.None;
jsonSerializationSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
Run Code Online (Sandbox Code Playgroud)
这是为了避免装饰每个Enum属性 [JsonConverter(typeof(StringEnumConverter))]
现在,如何选择退出某些Enum属性的全局序列化设置并使用转换为整数的默认序列化程序?
您可以将一个虚拟转换器添加到有问题的属性中,该虚拟转换器什么也不做:
public class NoConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
// Note - not called when attached directly via [JsonConverter(typeof(NoConverter))]
throw new NotImplementedException();
}
public override bool CanRead { get { return false; } }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanWrite { get { return false; } }
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用将其附加到属性[JsonConverter(typeof(NoConverter))]
。这样做之后,JsonConverter
属性的转换器取代了全局指定的转换器,但是由于CanRead
并且CanWrite
两者都返回false,因此不执行任何转换。对于枚举的集合,可以使用[JsonProperty(ItemConverterType = typeof(NoConverter))]
。
例如,如果您定义类型:
public enum Foo { A, B, C }
public class RootObject
{
[JsonConverter(typeof(NoConverter))]
public Foo FooAsInteger { get; set; }
public Foo FooAsString { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然后
var root = new RootObject { FooAsInteger = Foo.B, FooAsString = Foo.B };
var json = JsonConvert.SerializeObject(root, Formatting.Indented, new StringEnumConverter());
Console.WriteLine(json);
Run Code Online (Sandbox Code Playgroud)
产生输出
{
"FooAsInteger": 1,
"FooAsString": "B"
}
Run Code Online (Sandbox Code Playgroud)
请注意NoConverter
,如果要将所有数据模型中所有出现的枚举都序列化为整数,也可以直接应用于枚举:
[JsonConverter(typeof(NoConverter))]
public enum FooAlwaysAsInteger { A, B, C }
Run Code Online (Sandbox Code Playgroud)
样品提琴。
归档时间: |
|
查看次数: |
868 次 |
最近记录: |