简体   繁体   中英

how to handle enums like strings and ints

I'm rewriting an api, switching from newtonsoft.json to system.text.json, and an issue i have is the fact that in some cases we send enums as ints and sometimes as strings.

Consider this example:

{
"result":
{
"RequestTypeEnum":"Request.Get"
},
"resultTypeEnum": 0
}

How can I achieve this in system.text.json? I know that for pascal/camel case Json Naming Properties can be used, but I'm unaware how to handle enums differently in the same response

It may not be complete answer.

  1. Integer to Enum conversion automatically happen.

  2. For string to Enum you have to write your own convertor.

Following is the sample I tried.

class Program
{
    static async Task Main(string[] args)
    {
        
        string data = @"{
                        ""result"":
                        {
                                        ""RequestTypeEnum"":""Option""
                        },
                        ""resultTypeEnum"": 2
                        }";
        TempJson jsonObj =  System.Text.Json.JsonSerializer.Deserialize<TempJson>(data);
        Console.WriteLine();
        Console.ReadLine();
    }

   

    public class TempJson
    {
        [System.Text.Json.Serialization.JsonPropertyName("result")]
        
        public ChildObj Result { get; set; }
        [System.Text.Json.Serialization.JsonPropertyName("resultTypeEnum")]
        public ResultEnumType ResultTypeEnum { get; set; }
    }

    public class ChildObj
    {
        [System.Text.Json.Serialization.JsonConverter(typeof(CategoryJsonConverter))]
        public ResultEnumType RequestTypeEnum { get; set; }
    }

    public class CategoryJsonConverter : JsonConverter<ResultEnumType>
    {
        public override ResultEnumType Read(ref Utf8JsonReader reader,
                                      Type typeToConvert,
                                      JsonSerializerOptions options)
        {
            var name = reader.GetString();

            return (ResultEnumType)Enum.Parse(typeToConvert, name);
        }

        public override void Write(Utf8JsonWriter writer,
                                   ResultEnumType value,
                                   JsonSerializerOptions options)
        {
            writer.WriteStringValue(value.ToString());
        }
    }

    public enum ResultEnumType
    {
        Get,
        Post,
        Put,
        Delete,
        Option
    }
 }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM