Mark properties as required for deserialization with Microsoft's JsonSerializer in NET 6

39 Views Asked by At

I'm using microsoft's JsonSerializer
Attributes to mark properties as required have been introduced with .NET7
Unfortunately i'm working with .NET6

I need to detect when a property is missing from the input JSON but present in the C# class it's being deserialized to, either by having the deserializer throw an exception or through some other method.

    public class innerJModel {
        public int someProp {  get; set; }
    }
    public class JModel {
        public innerJModel innerJModel { get; set; }
    }
    public static void test() {
        JsonSerializerOptions FromJson_JsonSerOpts = new JsonSerializerOptions(JsonSerializerDefaults.General) {
            //NumberHandling = JsonNumberHandling.AllowReadingFromString | JsonNumberHandling.AllowNamedFloatingPointLiterals,
            AllowTrailingCommas = true,
            ReadCommentHandling = JsonCommentHandling.Skip,
            IncludeFields = false,
            //UnknownTypeHandling = JsonUnknownTypeHandling.JsonElement
        };
        JsonSerializerOptions ToJson_JsonSerOpts = new JsonSerializerOptions(JsonSerializerDefaults.General) {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
            DictionaryKeyPolicy = JsonNamingPolicy.CamelCase,
            //NumberHandling = JsonNumberHandling.Strict, //write numbers as numbers (never as quoted strings).
        };
        string jsonStr = @"{""innerJModel"":{""someProp"":12}}";
        var serRes = JsonSerializer.Deserialize<JModel>(jsonStr, FromJson_JsonSerOpts);
        Console.WriteLine(serRes.innerJModel?.someProp);
        Console.WriteLine(JsonSerializer.Serialize(serRes, ToJson_JsonSerOpts));

        string jsonStr2 = @"{""innerJModel"":{}}";
        var serRes2 = JsonSerializer.Deserialize<JModel>(jsonStr2, FromJson_JsonSerOpts); //this should fail, cuz a property defined in the C# class is missing from the JSON
        Console.WriteLine(JsonSerializer.Serialize(serRes2, ToJson_JsonSerOpts)); 
    }
0

There are 0 best solutions below