事实是123
可以分配给一个不包含值的枚举123
并不完全是 Json.Net 的错。事实证明,C# 运行时本身允许这种分配。如果您运行这个小演示程序,您可以亲自看到这一点:
class Program
{
static void Main(string[] args)
{
// Direct cast from integer -- no error here
MyEnum x = (MyEnum)123;
Console.WriteLine(x);
// Parsing a numeric string -- no error here either
MyEnum y = (MyEnum)Enum.Parse(typeof(MyEnum), "456");
Console.WriteLine(y);
}
public enum MyEnum
{
Zero = 0,
One = 1,
Two = 2
}
}
所以可能发生的情况是 Json.Net 只是使用Enum.Parse
在幕后。然而,我不知道为什么你的第一个案例没有得到例外。当我尝试这样做时,它失败了(正如我所期望的)。
无论如何,如果您需要严格验证可能错误的枚举值,您可以创建一个自定义JsonConverter
这将强制该值有效(或者可选地抛出异常)。这是一个适用于任何类型枚举的转换器。 (该代码可能可以改进,但它有效。)
class StrictEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType.BaseType == typeof(Enum));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JToken token = JToken.Load(reader);
try
{
// We're only interested in integers or strings;
// all other token types should fall through
if (token.Type == JTokenType.Integer ||
token.Type == JTokenType.String)
{
// Get the string representation of the token
// and check if it is numeric
string s = token.ToString();
int i;
if (int.TryParse(s, out i))
{
// If the token is numeric, try to find a matching
// name from the enum. If it works, convert it into
// the actual enum value; otherwise punt.
string name = Enum.GetName(objectType, i);
if (name != null)
return Enum.Parse(objectType, name);
}
else
{
// We've got a non-numeric value, so try to parse it
// as is (case insensitive). If this doesn't work,
// it will throw an ArgumentException.
return Enum.Parse(objectType, s, true);
}
}
}
catch (ArgumentException)
{
// Eat the exception and fall through
}
// We got a bad value, so return the first value from the enum as
// a default. Alternatively, you could throw an exception here to
// halt the deserialization.
IEnumerator en = Enum.GetValues(objectType).GetEnumerator();
en.MoveNext();
return en.Current;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}
这是一个在大杂烩值上使用转换器的演示:
class Program
{
static void Main(string[] args)
{
// The first 12 values should deserialize to correct values;
// the last 7 should all be forced to MyEnum.Zero.
string json = @"
{
""MyEnumList"":
[
""Zero"",
""One"",
""Two"",
0,
1,
2,
""zero"",
""one"",
""two"",
""0"",
""1"",
""2"",
""BAD"",
""123"",
123,
1.0,
null,
false,
true
]
}";
MyClass obj = JsonConvert.DeserializeObject<MyClass>(json,
new StrictEnumConverter());
foreach (MyEnum e in obj.MyEnumList)
{
Console.WriteLine(e.ToString());
}
}
public enum MyEnum
{
Zero = 0,
One = 1,
Two = 2
}
public class MyClass
{
public List<MyEnum> MyEnumList { get; set; }
}
}
这是输出:
Zero
One
Two
Zero
One
Two
Zero
One
Two
Zero
One
Two
Zero
Zero
Zero
Zero
Zero
Zero
Zero
顺便说一句,要将此转换器与 Web API 一起使用,您需要将此代码添加到您的Application_Start()
中的方法Global.asax.cs
:
JsonSerializerSettings settings = GlobalConfiguration.Configuration.Formatters
.JsonFormatter.SerializerSettings;
settings.Converters.Add(new StrictEnumConverter());