Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

c# - Can't get enum to convert to json properly using Json.NET

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...