Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing with Json.NET: how to require a property not being null?

Using Newtonsoft's Json.NET serializer, is it possible to require a property to contain a non-null value and throw an exception on serialization if this not the case? Something like:

public class Foo
{
    [JsonProperty("bar", SerializationRequired = SerializationRequired.DisallowNull)]
    public string Bar { get; set; }
}

I know it is possible to do this upon deserialization (using the Required property of JsonProperty), but I cannot find anything on this for serialization.

like image 428
Maxime Rossini Avatar asked Oct 30 '25 09:10

Maxime Rossini


1 Answers

This is now possible by setting the JsonPropertyAttribute to Required.Always.

This requires Newtonsoft 12.0.1+, which didn't exist at the time this question was asked.

The example below throws a JsonSerializationException ( "Required property 'Value' expects a value but got null. Path '', line 1, position 16." ):

void Main()
{
    string json = @"{'Value': null }";
    Demo res = JsonConvert.DeserializeObject<Demo>(json);
}

class Demo
{
    [JsonProperty(Required = Required.Always)]
    public string Value { get; set;}
}
like image 80
Brian Avatar answered Nov 01 '25 00:11

Brian