問題描述
我有一個枚舉:
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);
}
}
回到類的屬性,我把屬性放在 Animal 上:
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"或dog"這樣的預期值,而是看到了BlackBear"和Dog".如何讓 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
將讀取 <一個 rel="noreferrer">EnumMember
屬性.如果您將 enum
更改為此,它將序列化到您想要的值.
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
}
(作為一個小提示,由于 Animals
不是標志枚舉,它 應該是單數:Animal
.你應該考慮改成這個.)
(As a minor note, since Animals
isn't a flags enum, it should be singular: Animal
. You should consider changing it to this.)
這篇關于無法使用 Json.NET 將枚舉正確轉換為 json的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!