0

I am trying to deserialize my API request body to object.

My json looks like this:

{
"EmployeeId": 123,
"EmployeeName": "Tony",
"EmployeeType": "Contractor"
}

My Class looks like:
public class RequestDto
{
public int EmployeeId {get; set;}
public string EmployeeName {get; set;}
public EmployeeType {get; set;}
}

My EmployeeType Enum
public enum EmployeeType
{
Uknown,
FullTime,
Vendor
}

I am using .net core 3.1 and i have added newtonsoft converters stringEnumConverter() in my startup.cs as well. with the above json, im getting an error converting the value to enum. I want it to be converted to default enum value when there is an unknown string value which is not available in the enum class. Is there any way .net core/newtonsoft allows me to do it without adding any custom converters which inherits from StringEnumConverter().

abbs
  • 226
  • 2
  • 3
  • 12
  • Take a look at [Ignoring JSON enum value that doesn't exist in target model class during deserialization](https://stackoverflow.com/q/44528056/3744182) and [How can I ignore unknown enum values during json deserialization?](https://stackoverflow.com/q/22752075/3744182). In fact I think this is a duplicate of those two, agree? – dbc Dec 29 '20 at 16:17
  • you will have to use custom model binding with json.net. can you post your web api method code? – Laxmikant Dec 29 '20 at 16:20
  • @dbc what i want to avoid is a custom converter just checking if the evolved .net core and newtonsoft is handling such scenarios or not! – abbs Dec 29 '20 at 16:54
  • @abbs you could use exception handling as shown in [Ignoring JSON enum value that doesn't exist in target model class during deserialization](https://stackoverflow.com/q/44528056/3744182). But there is no configuration setting to do this automatically. – dbc Dec 29 '20 at 17:04
  • Newtonsoft doesn't provide the setting to provide the default value when deserialize an unknown value. You have to customize a class extends JsonConverter like dbc said. – Karney. Dec 30 '20 at 08:38
  • thank you for the suggestion will try this out @dbc – abbs Dec 30 '20 at 20:17

0 Answers0