SmartEnum icon indicating copy to clipboard operation
SmartEnum copied to clipboard

Handling nullable

Open JDCain opened this issue 3 years ago • 2 comments

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

JDCain avatar Sep 09 '21 14:09 JDCain

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."
    ]
  }
}

poneymusical avatar Mar 24 '22 16:03 poneymusical

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

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]

send2vinnie avatar May 24 '23 02:05 send2vinnie