当我的enum不匹配json属性中提供的字符串值时,我如何才能得到Json.net不抛出?
当我基于当前文档创建enum时,会发生这种情况,但是第三方API稍后会添加更多的enum值。
我很高兴将特殊值标记为Unknown或使用可空枚举,不匹配的值将返回null。
您可以使用自定义JsonConverter
来解决此问题。这是我使用来自Json.Net的StringEnumConverter
类的一些片段组合在一起的一个。它应该给你灵活的处理事情的方式,无论你决定。下面是它的工作原理:
- 如果在JSON中找到的值与枚举(字符串或整数)匹配,则使用该值。(如果值是整数,并且有多个可能的匹配,则使用其中的第一个。)
- 如果枚举类型为空,则将该值设置为空。
- 如果枚举有一个名为"Unknown"的值,则使用该值。
- 否则使用枚举的第一个值。
下面是代码。请随意更改以满足您的需要。
class TolerantEnumConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
Type type = IsNullableType(objectType) ? Nullable.GetUnderlyingType(objectType) : objectType;
return type.IsEnum;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
bool isNullable = IsNullableType(objectType);
Type enumType = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;
string[] names = Enum.GetNames(enumType);
if (reader.TokenType == JsonToken.String)
{
string enumText = reader.Value.ToString();
if (!string.IsNullOrEmpty(enumText))
{
string match = names
.Where(n => string.Equals(n, enumText, StringComparison.OrdinalIgnoreCase))
.FirstOrDefault();
if (match != null)
{
return Enum.Parse(enumType, match);
}
}
}
else if (reader.TokenType == JsonToken.Integer)
{
int enumVal = Convert.ToInt32(reader.Value);
int[] values = (int[])Enum.GetValues(enumType);
if (values.Contains(enumVal))
{
return Enum.Parse(enumType, enumVal.ToString());
}
}
if (!isNullable)
{
string defaultName = names
.Where(n => string.Equals(n, "Unknown", StringComparison.OrdinalIgnoreCase))
.FirstOrDefault();
if (defaultName == null)
{
defaultName = names.First();
}
return Enum.Parse(enumType, defaultName);
}
return null;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
private bool IsNullableType(Type t)
{
return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
}
下面是一个演示,它使用几个不同的枚举(一个有"Unknown"值,另一个没有)来完成转换器的步骤:
[JsonConverter(typeof(TolerantEnumConverter))]
enum Status
{
Ready = 1,
Set = 2,
Go = 3
}
[JsonConverter(typeof(TolerantEnumConverter))]
enum Color
{
Red = 1,
Yellow = 2,
Green = 3,
Unknown = 99
}
class Foo
{
public Status NonNullableStatusWithValidStringValue { get; set; }
public Status NonNullableStatusWithValidIntValue { get; set; }
public Status NonNullableStatusWithInvalidStringValue { get; set; }
public Status NonNullableStatusWithInvalidIntValue { get; set; }
public Status NonNullableStatusWithNullValue { get; set; }
public Status? NullableStatusWithValidStringValue { get; set; }
public Status? NullableStatusWithValidIntValue { get; set; }
public Status? NullableStatusWithInvalidStringValue { get; set; }
public Status? NullableStatusWithInvalidIntValue { get; set; }
public Status? NullableStatusWithNullValue { get; set; }
public Color NonNullableColorWithValidStringValue { get; set; }
public Color NonNullableColorWithValidIntValue { get; set; }
public Color NonNullableColorWithInvalidStringValue { get; set; }
public Color NonNullableColorWithInvalidIntValue { get; set; }
public Color NonNullableColorWithNullValue { get; set; }
public Color? NullableColorWithValidStringValue { get; set; }
public Color? NullableColorWithValidIntValue { get; set; }
public Color? NullableColorWithInvalidStringValue { get; set; }
public Color? NullableColorWithInvalidIntValue { get; set; }
public Color? NullableColorWithNullValue { get; set; }
}
class Program
{
static void Main(string[] args)
{
string json = @"
{
""NonNullableStatusWithValidStringValue"" : ""Set"",
""NonNullableStatusWithValidIntValue"" : 2,
""NonNullableStatusWithInvalidStringValue"" : ""Blah"",
""NonNullableStatusWithInvalidIntValue"" : 9,
""NonNullableStatusWithNullValue"" : null,
""NullableStatusWithValidStringValue"" : ""Go"",
""NullableStatusWithValidIntValue"" : 3,
""NullableStatusWithNullValue"" : null,
""NullableStatusWithInvalidStringValue"" : ""Blah"",
""NullableStatusWithInvalidIntValue"" : 9,
""NonNullableColorWithValidStringValue"" : ""Green"",
""NonNullableColorWithValidIntValue"" : 3,
""NonNullableColorWithInvalidStringValue"" : ""Blah"",
""NonNullableColorWithInvalidIntValue"" : 0,
""NonNullableColorWithNullValue"" : null,
""NullableColorWithValidStringValue"" : ""Yellow"",
""NullableColorWithValidIntValue"" : 2,
""NullableColorWithNullValue"" : null,
""NullableColorWithInvalidStringValue"" : ""Blah"",
""NullableColorWithInvalidIntValue"" : 0,
}";
Foo foo = JsonConvert.DeserializeObject<Foo>(json);
foreach (PropertyInfo prop in typeof(Foo).GetProperties())
{
object val = prop.GetValue(foo, null);
Console.WriteLine(prop.Name + ": " +
(val == null ? "(null)" : val.ToString()));
}
}
}
输出:NonNullableStatusWithValidStringValue: Set
NonNullableStatusWithValidIntValue: Set
NonNullableStatusWithInvalidStringValue: Ready
NonNullableStatusWithInvalidIntValue: Ready
NonNullableStatusWithNullValue: Ready
NullableStatusWithValidStringValue: Go
NullableStatusWithValidIntValue: Go
NullableStatusWithInvalidStringValue: (null)
NullableStatusWithInvalidIntValue: (null)
NullableStatusWithNullValue: (null)
NonNullableColorWithValidStringValue: Green
NonNullableColorWithValidIntValue: Green
NonNullableColorWithInvalidStringValue: Unknown
NonNullableColorWithInvalidIntValue: Unknown
NonNullableColorWithNullValue: Unknown
NullableColorWithValidStringValue: Yellow
NullableColorWithValidIntValue: Yellow
NullableColorWithInvalidStringValue: (null)
NullableColorWithInvalidIntValue: (null)
NullableColorWithNullValue: (null)
查看针对此问题存在的少量建议,它们都使用StringEnumConverter作为主干,但没有建议通过继承使用它。如果你的场景和我的一样,我正在使用第三方API响应,其中有大量可能的枚举值,这些值可能会随着时间的推移而变化。我只关心其中的10个值,所以所有其他值我都想使用默认值(如Unknown)。下面是我的enum转换器:
/// <inheritdoc />
/// <summary>
/// Defaults enum values to the base value if
/// </summary>
public class DefaultUnknownEnumConverter : StringEnumConverter
{
/// <summary>
/// The default value used to fallback on when a enum is not convertable.
/// </summary>
private readonly int defaultValue;
/// <inheritdoc />
/// <summary>
/// Default constructor. Defaults the default value to 0.
/// </summary>
public DefaultUnknownEnumConverter()
{}
/// <inheritdoc />
/// <summary>
/// Sets the default value for the enum value.
/// </summary>
/// <param name="defaultValue">The default value to use.</param>
public DefaultUnknownEnumConverter(int defaultValue)
{
this.defaultValue = defaultValue;
}
/// <inheritdoc />
/// <summary>
/// Reads the provided JSON and attempts to convert using StringEnumConverter. If that fails set the value to the default value.
/// </summary>
/// <param name="reader">Reads the JSON value.</param>
/// <param name="objectType">Current type that is being converted.</param>
/// <param name="existingValue">The existing value being read.</param>
/// <param name="serializer">Instance of the JSON Serializer.</param>
/// <returns>The deserialized value of the enum if it exists or the default value if it does not.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return base.ReadJson(reader, objectType, existingValue, serializer);
}
catch
{
return Enum.Parse(objectType, $"{defaultValue}");
}
}
/// <inheritdoc />
/// <summary>
/// Validates that this converter can handle the type that is being provided.
/// </summary>
/// <param name="objectType">The type of the object being converted.</param>
/// <returns>True if the base class says so, and if the value is an enum and has a default value to fall on.</returns>
public override bool CanConvert(Type objectType)
{
return base.CanConvert(objectType) && objectType.GetTypeInfo().IsEnum && Enum.IsDefined(objectType, defaultValue);
}
}
用法与其他示例相同:
[JsonConverter(typeof(DefaultUnknownEnumConverter))]
public enum Colors
{
Unknown,
Red,
Blue,
Green,
}
[JsonConverter(typeof(DefaultUnknownEnumConverter), (int) NotFound)]
public enum Colors
{
Red = 0,
Blue,
Green,
NotFound
}
如果您只关心反序列化,您可以做的另一件简单的事情是将enum字段定义为字符串,并添加另一个'get' only字段,该字段将字符串字段解析为已知值之一或'unknown'。这个字段应该是'JsonIgnore'。
您可以使用自定义StringEnumConverter,如下所示:
public class SafeStringEnumConverter : StringEnumConverter
{
public object DefaultValue { get; }
public SafeStringEnumConverter(object defaultValue)
{
DefaultValue = defaultValue;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return base.ReadJson(reader, objectType, existingValue, serializer);
}
catch
{
return DefaultValue;
}
}
}
那么你可以这样使用:
[JsonConverter(typeof(SafeStringEnumConverter), Unknown)]
public enum Colors
{
Unknown,
[EnumMember(Value = "MY_VALUE_1")]
MyValue,
[EnumMember(Value = "MY_VALUE_2")]
MyValue2
}
下面是Vignesh Chandramohan回答的一些示例代码。如果你只是反序列化的话,这当然是最简单的解决方案。
public class SampleClass
{
[JsonProperty("sampleEnum")] public string sampleEnumString;
[JsonIgnore]
public SampleEnum sampleEnum
{
get
{
if (Enum.TryParse<SampleEnum>(sampleEnumString, true, out var result))
{
return result;
}
return SampleEnum.UNKNOWN;
}
}
}
public enum SampleEnum
{
UNKNOWN,
V1,
V2,
V3
}
改进@BrianRogers我写了下面的代码,它通过了他所有的测试+它处理EnumAttribute问题!(我最近遇到了同样的可空枚举问题)
class TolerantEnumConverter : StringEnumConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
try
{
return base.ReadJson(reader, objectType, existingValue, serializer);
}
catch
{
if (IsNullableType(objectType))
return null;
//I would throw the exception, but to pass the tests
return Enum.Parse(objectType, Enum.GetNames(objectType).First());
}
}
private static bool IsNullableType(Type t)
{
if (t == null)
throw new ArgumentNullException(nameof(t));
return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
}