0

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

3
  • Why not use an enumconverter for one but not the other?
    – Caius Jard
    Commented Apr 5, 2021 at 9:02
  • @CaiusJard i need to use enumconverter globally because the input i get almost always uses enums as strings, and the responses are sometimes strings sometimes integers
    – Tom
    Commented Apr 5, 2021 at 10:08
  • 1
    i mean you can use different converters per property, so use eg a global one for one way but then per-property use a different converter for all those enums that dont follow the global rule
    – Caius Jard
    Commented Apr 5, 2021 at 11:29

1 Answer 1

1

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
    }
 }
1
  • Actually you're a bit off. If you add jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); the app will automatically serialize enums as strings. But your approach has showed me that i could add custom converters in places where i need them so that in my response i would have different handling of the enums
    – Tom
    Commented Apr 5, 2021 at 9:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.