how to handle enums like strings and ints

651 views Asked by At

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

1

There are 1 answers

1
dotnetstep On BEST ANSWER

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
    }
 }