0

In our system, we have this enum and you can see the value starts with 1, not 0.

public enum EndType
    {
        [Description("DAYEND")]
        DayEnd = 1,
        [Description("MONTHEND")]
        MonthEnd = 2
    }

Then we have a request object that exposed through a web api and you can see that the PerformanceEndType doesn't have a default value.

public class AnnualisedPerformanceRequest
    {
        public EndType PerformanceEndType { get; set; };

        public bool UseDateRestrictMethod { get; set; } = false;
    }

Then when people post this JSON request to our web API:

{
    "UseDateRestrictMethod": true
}

The PerformanceEndType property actually has a value 0, which is not in the enum values we defined.

Of course, we can put a default value on this property for this request.

However, as we have a fair amount of enum properties in different request objects, is it possible to have some JSON setting or something, so when we call JsonConvert.DeserializeObject(request), it can work out that for this enum, the default value is 1 not 0?

daxu
  • 3,514
  • 5
  • 38
  • 76
  • Is a custom converter viable? That would be my first approach... – germi Feb 13 '20 at 12:01
  • After bumping into this issue a few times in the past I got in the habit of any time an enum is deserilized in this manner to define an enum value for 0 of Unknown, then in code you can reject the request when an Unknown is the enum value. This helps define the difference between Not Initialized and Default enum value. – asawyer Feb 13 '20 at 18:48
  • You can use a custom JsonConverter to solve this problem. See [How can I ignore unknown enum values during json deserialization?](https://stackoverflow.com/q/22752075/10263) for an example. That question is really similar to yours. You can customize the converter in the first answer to meet your needs. – Brian Rogers Feb 13 '20 at 21:31

1 Answers1

0
JsonConvert.DeserializeObject<EndType>(request);

OR

JsonConvert.DeserializeObject<AnnualisedPerformanceRequest>(request);
Malakiya sanjay
  • 208
  • 2
  • 12