我正在使用Json.Net反序列化
我有一个具有此类枚举属性的c#类:
public enum MyEnum {
House,
Cat,
Dog
}
我拥有的杰森:
"MyEnum ": "House",
"MyEnum ": "Cat",
"MyEnum ": "Doc<woof>"
House
和Cat
反序列化,但Dog<woof>
当然不是。如何让Json.Net忽略或处理woof
?
答案 0 :(得分:2)
您将需要定义一个custom JsonConverter。这可能看起来像这样:
Transaction Id
然后使用[JsonConverter]属性装饰枚举:
class MyEnumConverter : JsonConverter<MyEnum>
{
public override MyEnum ReadJson(JsonReader reader, Type objectType, MyEnum existingValue, bool hasExistingValue, JsonSerializer serializer)
{
var token = reader.Value as string ?? reader.Value.ToString();
var stripped = Regex.Replace(token, @"<[^>]+>", string.Empty);
if (Enum.TryParse<MyEnum>(stripped, out var result))
{
return result;
}
return default(MyEnum);
}
public override void WriteJson(JsonWriter writer, MyEnum value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
}