无法获取枚举转换使用Json.NET正确JSON
我有一个枚举:
public enum Animal
{
Dog,
Cat,
BlackBear
}
我需要将其发送到三阶党的API。此API要求枚举值我送小写偶尔需要下划线。在一般情况下,他们需要的名称不匹配我用枚举命名约定
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.
在使用的 https://gooddevbaddev.wordpress.com/2013/08/26/deserializing-c-enums-using-json-net / ,我试图用一个自定义JsonConverter:
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; }
当我虽然运行程序时,它似乎完全忽略JsonConverter和,而不是看到预期值像black_bear或狗,我看BlackBear和狗。我怎样才能获得JsonConverter真正做到从枚举值的字符串名称转换我指定要替换价值?
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?
谢谢!
您不必编写自己的转换器。 Json.NET的 StringEnumConverter
会读 EnumMember
属性。如果你改变你的枚举
此,它会序列,从和你想要的值。
You don't need to write your own converter. Json.NET's StringEnumConverter
will read the EnumMember
attribute. If you change your enum
to this, it will serialize from and to the values you want.
[JsonConverter(typeof(StringEnumConverter))]
public enum Animals
{
[EnumMember(Value = "dog")]
Dog,
[EnumMember(Value = "cat")]
Cat,
[EnumMember(Value = "black_bear")]
BlackBear
}
(作为一个小纸条,因为动物
不是一个标志枚举,它应该是单数:动物
你应该考虑改变这一点。)
(As a minor note, since Animals
isn't a flags enum, it should be singular: Animal
. You should consider changing it to this.)