ardalis / SmartEnum

A base class for quickly and easily creating strongly typed enum replacements in C#.
MIT License
2.18k stars 170 forks source link

Handling nullable #178

Open JDCain opened 3 years ago

JDCain commented 3 years ago

I have an instance where I am trying to use SmartEnumValueConverter but since the value can be null it throws an error rather than settings the SmartType to null. How can this be handled?

Error: Newtonsoft.Json.JsonSerializationException : Error converting Null to SmartType.

Example:

{
   type: null
}

Type can be null, 0, 1, 2, etc.

[JsonConverter(typeof(SmartEnumValueConverter<SmartType, int>))]
public SmartType? Type { get; set; }
poneymusical commented 2 years ago

I have the same issue with System.Text.Json when deserializing a request body :

public sealed class Country : SmartEnum<Country, string>
{
    public string OfficialStateName { get; }
    public string Iso31661Code { get; }
    public string Iso31662Code { get; }

    private Country(string iso31661Code, string iso31662Code, string name, string officialStateName) : base(name, iso31661Code)
    {
        OfficialStateName = officialStateName;
        Iso31662Code = iso31662Code;
        Iso31661Code = iso31661Code;
    }

    public static Country BE => new(nameof(BE), "BEL", "Belgium", "The Kingdom of Belgium");
    public static Country FR => new(nameof(FR), "FRA", "France", "The French Republic");
}

with wiring :

builder.Services.AddControllers()
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new SmartEnumValueConverter<Country, string>());
    });

Gives me:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "traceId": "00-1821f5005758ca0917218f173d02748e-fa2d3c48c1375cec-00",
  "errors": {
    "command": [
      "The command field is required."
    ],
    "$.address.country": [
      "Error converting value 'BE' to a smart enum."
    ]
  }
}
send2vinnie commented 1 year ago

Specify not to do the serialization/deserialization to the properties with null value by using the following attribute:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]