I have an enum:
public enum Animal
{
Dog,
Cat,
BlackBear
}
I need to send it to a third-party API. This API requires that the enum values I send be lower case and occasionally require underscores. In general, the names they require don't match the enum naming convention I use.
Using the example provided at https://gooddevbaddev.wordpress.com/2013/08/26/deserializing-c-enums-using-json-net/, I tried to use a custom JsonConverter:
public class AnimalConverter : JsonConverter {
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
var animal = (Animal)value;
switch (animal)
{
case Animal.Dog:
{
writer.WriteValue("dog");
break;
}
case Animal.Cat:
{
writer.WriteValue("cat");
break;
}
case Animal.BlackBear:
{
writer.WriteValue("black_bear");
break;
}
}
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
var enumString = (string)reader.Value;
Animal? animal = null;
switch (enumString)
{
case "cat":
{
animal = Animal.Cat;
break;
}
case "dog":
{
animal = Animal.Dog;
break;
}
case "black_bear":
{
animal = Animal.BlackBear;
break;
}
}
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(string);
}
}
Back in the properties of a class, I put the attributes on the Animal as so:
[JsonProperty("animal")]
[JsonConverter(typeof(AnimalConverter))]
public Animal ZooAnimals { get; set; }
When I run the program though, it seems to completely ignore the JsonConverter and rather than seeing expected values like "black_bear" or "dog", I see "BlackBear" and "Dog". How can I get the JsonConverter to actually do the conversion from the name of the enum value to the string I specify to replace that value with?
Thanks!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…