0

I'd like deserialization to fail for the following model:

class ExampleModel
{
    public ExampleEnum ExampleEnum { get; set; }

    public string ExampleString { get; set; }
}

enum ExampleEnum
{
    Value1,
    Value2,
}

when the ExampleEnum's value is not explicitly specified, i.e.:

{
    "ExampleString " : "abc"
}

It seems that it falls back to the default enum's value by, well, default:

string json = "{ \"exampleString\" : \"abc\" }";
var model = JsonSerializer.Deserialize<ExampleModel>(json);
Console.WriteLine(model.ExampleEnum); // outputs "Value1"

Is it possible to change the behavior?

alexalok
  • 107
  • 2
  • 12
  • 1
    It's not currently implemented out of the box. See [Implement a concept of "Required" properties #29861](https://github.com/dotnet/runtime/issues/29861). – dbc Nov 07 '20 at 18:23

1 Answers1

0

Unfortunately I didn't find a easy way to do it. Unlike newtonsoft.json , system.text.json does not has this feature built in. The only way seems to be to write a custom converter.

Here is how your custom converter code should look like.

public class ExampleModelRequiredPropertyConverter : JsonConverter<ExampleModel>
{
    public override ExampleModel Read(ref Utf8JsonReader reader,Type type,JsonSerializerOptions options)
    {
        ExampleModel model = JsonSerializer.Deserialize<ExampleModel>(ref reader);
        
        if (model.ExampleEnum == default)
        {
            throw new JsonException("Required property not received in the JSON");
        }
        return model;
    }
    
    public override void Write(Utf8JsonWriter writer,ExampleModel model, JsonSerializerOptions options)
    {
        JsonSerializer.Serialize(writer, model);
    }
}

After defining the converter you need to add the converter to the JsonSerializerOptions.Converters collection so that it gets registered. You cannot register this converter as an attribute as that will result in Stack Overflow exception.

If you want to use the converter as an attribute these is an alternate approach defined here in the Microsoft docs. This doc also talks about the above mentioned approach.

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
Ben
  • 356
  • 4
  • 12