I am using Json.Net to deserialize
I have ac# class that has a property of this type of enum:
public enum MyEnum {
House,
Cat,
Dog
}
The Json I have:
"MyEnum ": "House",
"MyEnum ": "Cat",
"MyEnum ": "Doc<woof>"
House
and Cat
deserializes, but Dog<woof>
of course doesn't. How can I get Json.Net to ignore or handle the woof
?
You will need to define a custom JsonConverter . This might look something like this:
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());
}
}
Then decorate your enum with a [JsonConverter] attribute:
[JsonConverter(typeof(MyEnumConverter))]
enum MyEnum
{
House,
Dog,
Cat,
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.